1

我有这样的输入行:

1 soccer ball at 10
2 Iphones 4s at 199.99
4 box of candy at 50

我想得到第一个数字,商品本身和价格(我不想要“at”)。

我已经完成了以下正则表达式:

/^(\d+)\sat\s(\d+\.?\d*)$/

但正如你所看到的,我错过了“at”之前的内容。我应该放什么?

4

4 回答 4

3

这应该适合你。

/(\d+)\s+(.+?)\s+at\s+([\d\.,]+)/

于 2012-10-27T12:34:27.957 回答
1

这是我的版本:

// double escaped \ as it's supposed to be in PHP
'~(\\d+)\\s+(.+?)\\s+at\\s+(\\d+(?:,\\d+)?(?:\\.\\d+)?)~'
// catches thousands too but stays strict about the order of , and .

干杯!

PS:编码超过 100 万美元的产品可能会失败:)

于 2012-10-27T13:05:36.843 回答
0
/^(\d+)\s(.+?)\sat\s(\d+\.?\d*)$/

应该管用。

于 2012-10-27T12:34:15.003 回答
0

正则表达式演示

在这里你有(\d+)\s([\w ]+)\sat\s(\d+(?:\.\d+)?)

正如您在演示中看到的,解释

/(\d+)\s([\w ]+)\sat\s(\d+(?:\.\d+)?)/g
1st Capturing group (\d+) 
    \d infinite to 1 times. Digit [0-9] 
\s Whitespace [\t \r\n\f] 
2nd Capturing group ([\w ]+) 
    Char class [\w ] infinite to 1 times. matches one of the following chars: \w 
        \w Word character [a-zA-Z_\d] 
\s Whitespace [\t \r\n\f] 
at Literal `at`
\s Whitespace [\t \r\n\f] 
3rd Capturing group (\d+(?:\.\d+)?) 
    \d infinite to 1 times. Digit [0-9] 
    Group (?:\.\d+) 1 to 0 times. 
        \. Literal `.`
        \d infinite to 1 times. Digit [0-9] 

g 修饰符:全局。所有比赛(第一场比赛不返回)

于 2012-10-27T12:35:19.840 回答