正则表达式不会在第一个空格处停止 [英] Regex not stopping at first space
问题描述
尝试创建一个匹配左括号的模式,并获取它和它遇到的下一个空间之间的所有内容.我认为 \[.*\s
会实现这一点,但它从第一个左括号开始就获得了所有内容.我怎么能告诉它在下一个空间中断?
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?
推荐答案
\[[^\s]*\s
.*
是贪婪的,会吃掉所有东西,包括空格,直到最后一个空格字符.如果您将其替换为 \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.
可能需要屏蔽左括号.如果你用 ^\s 否定 \s,表达式应该吃除空格之外的所有东西,然后是一个空格,这意味着直到第一个空格.
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.
这篇关于正则表达式不会在第一个空格处停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!