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 に答える