匹配多个可选字符,这取决于彼此。

时间:2021-12-02 13:15:25

I want to match all valid prefixes of substitute followed by other characters, so that

我想匹配所有有效的替换前缀后面跟着其他字符,这样

  • sub/abc/def matches the sub part.
  • sub/abc/def与sub - part相匹配。
  • substitute/abc/def matches the substitute part.
  • 替换/abc/def匹配替换部分。
  • subt/abc/def either doesn't match or only matches the sub part, not the t.
  • subt/abc/def不是不匹配就是只匹配子部分,而不是t。

My current Regex is /^s(u(b(s(t(i(t(u(te?)?)?)?)?)?)?)?)?/, which works, however this seems a bit verbose.

我现在的正则表达式/ ^ s(u(b(s(t(我(t(u(te)?)?)?)?)?)?)吗?)?/,但这似乎有点啰嗦。

Is there any better (as in, less verbose) way to do this?

有没有更好的方法(比如,少一点啰嗦)来做这件事?

2 个解决方案

#1


1  

you could use a two-step regex

您可以使用两步regex

  1. find first word of subject by using this simple pattern ^(\w+)
  2. 找到第一个词的主题使用这个简单的模式^(\ w +)
  3. use the extracted word from step 1 as your regex pattern e.g. ^subs against the word substitute
  4. 用提取的词从步骤1你的正则表达式模式例如^潜艇对这个词替代

#2


2  

This would do like the same as you mentioned in your question.

这和你在问题中提到的一样。

^s(?:ubstitute|ubstitut|ubstitu|ubstit|ubsti|ubst|ubs|ub|u)?

The above regex will always try to match the large possible word. So at first it checks for substitute, if it finds any then it will do matching else it jumps to next pattern ie, substitut , likewise it goes on upto u.

上面的regex将始终尝试匹配较大的可能单词。所以一开始它检查替换,如果找到了,它会进行匹配否则它会跳转到下一个模式ie,替换,同样地,它会一直到u。

DEMO 1 DEMO 2

演示1演示2

#1


1  

you could use a two-step regex

您可以使用两步regex

  1. find first word of subject by using this simple pattern ^(\w+)
  2. 找到第一个词的主题使用这个简单的模式^(\ w +)
  3. use the extracted word from step 1 as your regex pattern e.g. ^subs against the word substitute
  4. 用提取的词从步骤1你的正则表达式模式例如^潜艇对这个词替代

#2


2  

This would do like the same as you mentioned in your question.

这和你在问题中提到的一样。

^s(?:ubstitute|ubstitut|ubstitu|ubstit|ubsti|ubst|ubs|ub|u)?

The above regex will always try to match the large possible word. So at first it checks for substitute, if it finds any then it will do matching else it jumps to next pattern ie, substitut , likewise it goes on upto u.

上面的regex将始终尝试匹配较大的可能单词。所以一开始它检查替换,如果找到了,它会进行匹配否则它会跳转到下一个模式ie,替换,同样地,它会一直到u。

DEMO 1 DEMO 2

演示1演示2