Reputation: 574
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?
Upvotes: 17
Views: 22464
Reputation: 36229
\[[^\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.
Upvotes: 23
Reputation: 5211
You want to replace .
with [^\s]
, this would match "not space" instead of "anything" that .
implies
Upvotes: 2
Reputation: 12920
I suggest using \[\S*(?=\s)
.
\[
: Match a [
character.\S*
: Match 0 or more non-space characters.(?=\s)
: Match a space character, but don't include it in the pattern. This feature is called a zero-width positive look-ahead assertion and makes sure you pattern only matches if it is followed by a space, so it won't match at the end of line.You might get away with \[\S*\s
if you don't care about groups and want to include the final space, but you would have to clarify exactly which patterns need matching and which should not.
Upvotes: 3
Reputation: 174299
Use this:
\[[^ ]*
This matches the opening bracket (\[
) and then everything except space ([^ ]
) zero or more times (*
).
Upvotes: 3
Reputation: 41757
You could use a reluctant qualifier:
[.*?\s
Or instead match on all non-space characters:
[\S*\s
Upvotes: 7