Regex not stopping at first space

后端 未结 5 1724
说谎
说谎 2021-01-05 03:20

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 th

相关标签:
5条回答
  • 2021-01-05 03:38

    Use this:

    \[[^ ]*
    

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

    0 讨论(0)
  • 2021-01-05 03:40

    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.

    0 讨论(0)
  • 2021-01-05 03:40

    You want to replace . with [^\s], this would match "not space" instead of "anything" that . implies

    0 讨论(0)
  • 2021-01-05 03:47

    You could use a reluctant qualifier:

    [.*?\s
    

    Or instead match on all non-space characters:

    [\S*\s
    
    0 讨论(0)
  • 2021-01-05 03:54
    \[[^\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.

    0 讨论(0)
提交回复
热议问题