正则表达式匹配条件字符串

例如,如果我有以下字符串:

99%89 (should match)
99%? (should match)
?%99 (should match)
?%? (should not match)
?%99%99 (should match)
99%99%99%? (should match)

本质上,第一个或第二个元素可以是 ? 或一个数字,但两个元素都不能是 ?。我试着想像这样的事情:

[0-9]*|[?](?!?)[%][0-9]*|[?]

但这不会产生正确的答案,任何帮助将不胜感激

回答

使用您显示的样本,您能否尝试以下操作。

^(?:(?:?(?:(?:%d+){1,})?)|(?:(?:(?:d+%){1,})??(?:(?:%d+){1,})?)|(?:d+%d+))$

上述正则表达式的在线演示

说明:为以上添加详细说明。

^(?:                       ##Matching from starting of the value, starting a non-capturing group from here.
 (?:?                     ##Starting non-capturing group(one for understanding purposes) matching literal ? here.
    (?:(?:%d+){1,})?      ##In a non capturing group looking for % with 1 or more occurrences of digits and matching this group match keeping it optional.
  )|                       ##Closing one non-capturing group here, with OR condition here.
 (?:                       ##Starting non-capturing group(two) here.
    (?:(?:d+%){1,})??    ##Looking for digits with % one or more occurrences in a non-capturing group keeping it optional followed by ?
    (?:(?:%d+){1,})?      ##Checking for % digits one or more occurrences in a non-capturing group keeping it optional followed by ?
 )|                        ##Closing two non-capturing group here, with OR condition here.
 (?:d+%d+)               ##In a non-capturing group looking for 1 or more digits % one or more digits
)$                         ##Closing  1st non-capturing group at the end of value.


以上是正则表达式匹配条件字符串的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>