2

I need to parse some text, which consists of a six digit code, an optional confirmation string (one of 'ok', 'yes' or 'no'), followed by some free text. So it might look like:

123456 Ok Mary had a little lamb

... but might equally be

123456 Mary had a little lamb

...and I'd need each of those three parts captured separately.

I've got this regex:

/^\s*?(\d\d\d\s?\d\d\d)\s*?(yes|no|ok)?\s*?(.*?)$/i

...which doesn't work! I can tweak it so that it works if you always have the 'yes', 'no' or 'ok', but that is an optional element.

Any thoughts very much appreciated.

4

1 回答 1

4

你的问题是这\s*?没有意义,你想要\s*:因为*意味着 0 或更多,它已经使空间成为可选的。

利用

/^\s*?(\d{3}\s?\d{3})\s*(yes|no|ok)?\s*(.*)$/i

例如在 JavaScript 中,

var str = '123456 Ok Mary had a little lamb';
var arr = str.match(/^\s*?(\d{3}\s?\d{3})\s*(yes|no|ok)?\s*(.*)$/i).slice(1);

["123456", "Ok", " Mary had a little lamb"]
于 2013-09-12T16:42:19.563 回答