Regex 要查找的正则表达式
我想要一个不区分大小写的表达式,它在逻辑上可以找到: (stringA或stringB)和stringC 因此,如果stringA是“dr”,stringB是“doctor”,stringC是“presume”,我希望得到以下结果:Regex 要查找的正则表达式,regex,Regex,我想要一个不区分大小写的表达式,它在逻辑上可以找到: (stringA或stringB)和stringC 因此,如果stringA是“dr”,stringB是“doctor”,stringC是“presume”,我希望得到以下结果: Dr. Livinsgston I presume TRUE Doctor Livingston I presume TRUE Mr. Livingston I presume FALSE 值在测试字符串中
Dr. Livinsgston I presume TRUE
Doctor Livingston I presume TRUE
Mr. Livingston I presume FALSE
值在测试字符串中的位置并不重要,但是如果我可以让表达式要求(A或B)在测试字符串中的C之前,那就更好了
这在regexp中可行吗?在regex中非常可行,但在这种情况下绝对没有理由使用regex。您没有添加语言,因此这里有一个简单的python解决方案:
def check_string(test_string):
lowered_string = test_string.lower()
doctor = lambda s: "dr" in s or "doctor" in s
presume = lambda s: "presume" in s
return doctor(lowered_string) and presume(lowered_string)
一般来说,只要有可能,您都希望避免使用正则表达式,并且只需对字符串的小写版本进行检查,就可以轻松地使检查不区分大小写(就像我上面所做的那样)
如果您想将其与正则表达式匹配,这里有一个版本的d'alar'cop的答案,它实际上是有效的(移动到python以保持我的答案在内部的一致性):
是的,您可以使用regexp执行此操作。有了grep,你可以简单地做到这一点
echo Doctor Livinsgston I presume | grep "^\(Dr\.\|Doctor\).*presume$" >/dev/null; [[ $? == 0 ]] && echo TRUE || echo FALSE
TRUE
echo Dr. Livinsgston I presume | grep "^\(Dr\.\|Doctor\).*presume$" >/dev/null; [[ $? == 0 ]] && echo TRUE || echo FALSE
TRUE
echo Mr. Livinsgston I presume | grep "^\(Dr\.\|Doctor\).*presume$" >/dev/null; [[ $? == 0 ]] && echo TRUE || echo FALSE
FALSE
上面发布的Python解决方案完成了这项工作;但如果您也只是想学习如何做类似的事情,那么这里有一个可能的解决方案(在JavaScript中;其他语言的语法可能有所不同): 末尾的
i
使其不区分大小写(相当于预先将测试字符串转换为小写)。括号中单词之间的|
使这两个单词可以互换。*?
只是意味着括号中的内容和假设之间几乎可以有任何区别
注意,这意味着presume
必须在括号中的内容之前。老实说,如果顺序很重要的话,你在正则表达式上会遇到很多麻烦 在Perl中,您可以执行以下操作:
(?:[Dd]r|Doctor).*(?:presume)
正则表达式:
(?: group, but do not capture:
[Dd] any character of: 'D', 'd'
r match 'r'
| OR
Doctor match 'Doctor'
) end of grouping
.* any character except \n (0 or more times)
(?: group, but do not capture (1 or more times)
presume match 'presume'
) end of grouping
对断言的简短解释。看
(?=)正向前瞻断言
(?!)消极前瞻断言
(?什么味道..javascript?java?php?例如,stringC必须排在stringA/stringB之后,或者它们可以以任何顺序出现?我还想说,正则表达式并不是解决这个问题的唯一方法--根据您相当简单的标准,您可以通过几个简单的in_string()
调用获得相同的结果(或您使用的任何语言的相关函数)是的,或者拆分后包含一些内容你尝试过正则表达式吗?试着自己编写一些东西,如果它不起作用,请将它带给我们以帮助你。你启动它,我们帮助。我们不为你编写它。向我们展示你尝试过的实际代码,然后我们可以从那里帮助你。很可能你会非常接近它如果你先自己尝试一下,答案就是。
(?:[Dd]r|Doctor).*(?:presume)
(?: group, but do not capture:
[Dd] any character of: 'D', 'd'
r match 'r'
| OR
Doctor match 'Doctor'
) end of grouping
.* any character except \n (0 or more times)
(?: group, but do not capture (1 or more times)
presume match 'presume'
) end of grouping
(?=) Positive look ahead assertion
(?!) Negative look ahead assertion
(?<=) Positive look behind assertion
(?<!) Negative look behind assertion
(?>) Once-only subpatterns
(?(x)) Conditional subpatterns
(?#) Comment (?# Pattern does x y or z)