问题描述
在下面的例子中,我试图匹配 s
或季节
,但我已经匹配 s
, e
, a
, o
和 n
。
[s | season]
如何使正则表达式匹配整个单词?
方括号表示对于字符类,您实际上正在尝试匹配以下任何一项: s
, |
, s
(再次), e
, a
,
(再次), o
和 n
。
使用括号代替分组:
(s | season)
或非捕获组:
(?: s | season)
注意:非捕获组告诉引擎它不需要存储匹配,而另一个(捕获组)。对于小的东西,无论是工作,对于重型的东西,你可能希望先看看是否需要比赛。如果没有,请更好地使用非捕获组来分配更多的内存用于计算,而不是存储您将永远不需要使用的内容。
I want to match a regular expression on a whole word.
In the following example I am trying to match s
or season
but what I have matches s
, e
, a
, o
and n
.
[s|season]
How do I make a regular expression to match a whole word?
Square brackets are meant for character class, and you're actually trying to match any one of: s
, |
, s
(again), e
, a
, s
(again), o
and n
.
Use parentheses instead for grouping:
(s|season)
or non-capturing group:
(?:s|season)
Note: Non-capture groups tell the engine that it doesn't need to store the match, while the other one (capturing group does). For small stuff, either works, for 'heavy duty' stuff, you might want to see first if you need the match or not. If you don't, better use the non-capture group to allocate more memory for calculation instead of storing something you will never need to use.
这篇关于正则表达式匹配一个字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!