英文:
How do I make whole words optional in the regex?
问题
我想自定义我的正则表达式来识别以下内容:apple and lemon
,apple lemon
,apple and
和apple
。我希望and
和lemon
这两个词是可选的,目前我只能让and
可选,但不能让lemon
可选。
如果能够在当前的正则表达式格式下实现这个目标就太好了。
正则表达式:
\b([a][\W_]*?)+([\W_]*?)+(
[\W_]*?)+([l][\W_]*?)+([e][\W_]*?)+(([a][\W_]*?)+([n][\W_]*?)+([d][\W_]*?))?([l][\W_]*?)+([e][\W_]*?)+([m][\W_]*?)+([o][\W_]*?)+([n][\W_]*?)+\b
Regex101链接:
https://regex101.com/r/Wte6Gg/2
英文:
Namely, I wanted to customize my regex to recognize the following things apple and lemon
, apple lemon
, apple and
and apple
. I want the words and
and lemon
to be optional, currently I only managed to make and
optional but not lemon
.
It would be great if it's achievable with the current format of the regex.
Regex:
\b([a][\W_]*?)+([\W_]*?)+(
[\W_]*?)+([l][\W_]*?)+([e][\W_]*?)+(([a][\W_]*?)+([n][\W_]*?)+([d][\W_]*?))?([l][\W_]*?)+([e][\W_]*?)+([m][\W_]*?)+([o][\W_]*?)+([n][\W_]*?)+\b
Regex101:
答案1
得分: 2
以下是翻译好的内容:
以下表达式需要以“apple”开头,然后可以跟随“lemon”和“and”这两个词,如果它们都跟随,它们需要按照“and lemon”的顺序排列。
这对你有帮助吗?
\b(apple)( ?and)?( ?lemon)?\b
https://regex101.com/r/gyj0yY/1
编辑
按照你的格式,以下表达式应该可以工作:
[\W_]*?)+( [\W_]*?)+([l][\W_]*?)+([e][\W_]*?)+(([\W_]*)([a][\W_]*?)+([n][\W_]*?)+([d][\W_]*?)+)?(([\W_]*)([l][\W_]*?)+([e][\W_]*?)+([m][\W_]*?)+([o][\W_]*?)+([n][\W_]*?)+)?\b\b([a][\W_]*?)+(
https://regex101.com/r/5wPyJ1/1
如果这是你要找的内容,请将其标记为答案。
英文:
The following expression needs to start with "apple", then the words "lemon" and "and" can follow, if they follow both, they need to be in the order "and lemon"
Does that help?
\b(apple)( ?and)?( ?lemon)?\b
https://regex101.com/r/gyj0yY/1
EDIT
In your format the following should work:
[\W_]*?)+( [\W_]*?)+([l][\W_]*?)+([e][\W_]*?)+(([\W_]*)([a][\W_]*?)+([n][\W_]*?)+([d][\W_]*?)+)?(([\W_]*)([l][\W_]*?)+([e][\W_]*?)+([m][\W_]*?)+([o][\W_]*?)+([n][\W_]*?)+)?\b\b([a][\W_]*?)+(
https://regex101.com/r/5wPyJ1/1
If that is what you were looking for, please mark it as the answer.
答案2
得分: 1
这是一个更通用的解决方案-使用两个单词,可选择用"and"连接。
https://regex101.com/r/Z2TZ7T/1
英文:
This is a more general solution - using two words, optionally joined by an 'and'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论