Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex not stopping at first space

Tags:

regex

Trying to create a pattern that matches an opening bracket and gets everything between it and the next space it encounters. I thought \[.*\s would achieve that, but it gets everything from the first opening bracket on. How can I tell it to break at the next space?

like image 356
HashTagDevDude Avatar asked Feb 17 '12 14:02

HashTagDevDude


3 Answers

\[[^\s]*\s

The .* is a greedy, and will eat everything, including spaces, until the last whitespace character. If you replace it with \S* or [^\s]*, it will match only a chunk of zero or more characters other than whitespace.

Masking the opening bracket might be needed. If you negate the \s with ^\s, the expression should eat everything except spaces, and then a space, which means up to the first space.

like image 78
user unknown Avatar answered Nov 02 '22 06:11

user unknown


You could use a reluctant qualifier:

[.*?\s

Or instead match on all non-space characters:

[\S*\s
like image 24
Rich O'Kelly Avatar answered Nov 02 '22 05:11

Rich O'Kelly


Use this:

\[[^ ]*

This matches the opening bracket (\[) and then everything except space ([^ ]) zero or more times (*).

like image 32
Daniel Hilgarth Avatar answered Nov 02 '22 04:11

Daniel Hilgarth