匹配单词或其前缀的正则表达式 [英] Regular expression to match a word or its prefix

查看:1168
本文介绍了匹配单词或其前缀的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在整个单词上匹配一个正则表达式.

I want to match a regular expression on a whole word.

在下面的示例中,我尝试匹配sseason,但是我匹配的是seaon.

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?

推荐答案

方括号用于字符类,您实际上正在尝试匹配以下任何一项:s|s(再次),eas(再次),on.

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.

使用括号代替分组

(s|season)

或非捕获组:

(?:s|season)


注意:非捕获组告诉引擎它不需要存储匹配项,而另一组(捕获组则需要存储).对于小东西,无论哪种都可以,对于重型"东西,您可能想先看看是否需要火柴.如果不这样做,最好使用non-capture组分配更多的内存进行计算,而不要存储不需要使用的内容.


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.

这篇关于匹配单词或其前缀的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆