[英]Regex X and/or Y
Consider the following regular expression, where X
and Y
are any regex. 考虑以下正则表达式,其中
X
和Y
是任何正则表达式。
XY|YX|X|Y
This regex tests for X
and/or Y
, but has to double-check expressions if the "and" clause is not found. 此正则表达式测试
X
和/或Y
,但如果找不到“和”子句,则必须仔细检查表达式。
What is the best way to match X
and/or Y
? 匹配
X
和/或 Y
的最佳方法Y
什么?
The regex /XY?|YX?/
should work to match each of the four situations you listed. 正则表达式
/XY?|YX?/
应该与您列出的四种情况相匹配。 This is limited however, as if the regex you use have a common match, you may get unexpected results. 但这是有限的,就像你使用的正则表达式有一个共同的匹配,你可能会得到意想不到的结果。
With limited information, comes limited solutions
信息有限,有限的解决方案
If this is an issue, perhaps add more requirements to the question. 如果这是一个问题,可能会在问题中添加更多要求。
Explanation: 说明:
The first half will attempt to match the X
regex then will attempt to match the Y
regex 0
or 1
times. 前半部分将尝试匹配
X
正则表达式,然后尝试匹配Y
正则表达式0
或1
次。 If the X
regex fails, then it will try the second half; 如果
X
正则表达式失败,那么它将尝试下半部分; which will attempt to match the Y
regex then will attempt to match the X
regex 0
or 1
times. 将尝试匹配
Y
正则表达式然后将尝试匹配X
正则表达式0
或1
次。
[XY]+
to get any number of Xs and Ys (so includes XYYXYX
, etc). [XY]+
获取任意数量的X和Y(因此包括XYYXYX
等)。
Or... 要么...
[XY]{1,2}
to select 1-2 Xs and Ys (which only includes your 4 examples). [XY]{1,2}
选择1-2个X和Y(仅包括您的4个示例)。
For your requirement of X and/or Y
how about this regex: 对于你的
X and/or Y
要求,这个正则表达式怎么样:
(?:(?=.*?X)|(?=.*?Y))(X|Y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.