The regular expression does not stop in the first space

Trying to create a template that matches the opening bracket, and gets everything between it and the next place it meets. I thought that \[.*\s would achieve this, but it gets everything from the first open bracket. How can I tell it to crash into the next space?

+6
source share
5 answers
 \[[^\s]*\s 

.* is greedy and will eat everything, including spaces, to the last space character. If you replace it with \S* or [^\s]* , it will only match a fragment of zero or more characters except spaces.

It may be necessary to mask the open bracket. If you negate \ s with ^ \ s, the expression should have everything except spaces, and then a space, which means up to the first space.

+5
source

You can use a reluctant classifier:

 [.*?\s 

Or instead of matches for all non-spatial characters:

 [\S*\s 
+4
source

Use this:

 \[[^ ]* 

This corresponds to an opening bracket ( \[ ), and then everything but a space ( [^ ] ), zero or more ( * ).

+3
source

I suggest using \[\S*(?=\s) .

  • \[ : match the character [ .
  • \S* : Match 0 or more non-space characters.
  • (?=\s) : match the space character, but do not include it in the pattern. This function is called positive forward with zero width and ensures that the pattern will only match if it is followed by a space, so it will not match at the end of the line.

You can leave with \[\S*\s if you do not like groups and want to include a finite space, but you will need to determine exactly which patterns should and should not.

+3
source

You want to replace . on [^\s] , this will match "no space" instead of "nothing" that . means

+1
source

Source: https://habr.com/ru/post/908708/


All Articles