如何在正则表达式中使整个单词可选?

huangapple go评论80阅读模式
英文:

How do I make whole words optional in the regex?

问题

我想自定义我的正则表达式来识别以下内容:apple and lemonapple lemonapple andapple。我希望andlemon这两个词是可选的,目前我只能让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:

https://regex101.com/r/Wte6Gg/2

答案1

得分: 2

以下是翻译好的内容:

以下表达式需要以“apple”开头,然后可以跟随“lemon”和“and”这两个词,如果它们都跟随,它们需要按照“and lemon”的顺序排列。
这对你有帮助吗?

\b(apple)( ?and)?( ?lemon)?\b

https://regex101.com/r/gyj0yY/1


编辑

按照你的格式,以下表达式应该可以工作:

\b([a][\W_]*?)+(

[\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

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:

\b([a][\W_]*?)+(

[\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

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'

https://regex101.com/r/Z2TZ7T/1

如何在正则表达式中使整个单词可选?

huangapple
  • 本文由 发表于 2023年7月17日 07:35:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76700811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定