[英]Regular expression match multiple substring
I have written a regular expression to test how a string is a logical expression or not. 我编写了一个正则表达式来测试字符串是否是逻辑表达式。 Here is the regular expression:
这是正则表达式:
/(.*)(<|>|<=|>=|=|!=)(.*)/
And here is the subject which I tested with the expression above: 这是我用上面的表达式测试的主题:
3!=2
The preg_match_all
function in PHP return the following array: PHP中的
preg_match_all
函数返回以下数组:
[
[
"3!=2"
],
[
null
],
[
"="
],
[
"2"
]
]
I got a wrong logical operator because it's not match only the =
pattern but also match the !=
operator. 我有一个错误的逻辑运算符,因为它不匹配
=
pattern而且匹配!=
运算符。 How should I rewrite the regular expression to not match multiple strings in the brackets? 我应该如何重写正则表达式以匹配括号中的多个字符串?
You should exclude <>!
你应该排除
<>!
before the operator and =
after operator. 在操作员之前和
=
操作员之后。 Then, just to shorten, group the operators tighter. 然后,只是缩短,将操作员分组更紧。
([^<>!]*)([<>]=?|!?=)([^=]*)
You could also shorten it a bit with this: 你也可以用它来缩短它:
(\w+)([<>]=?|!?=)(\w+)
With <=>
, use 使用
<=>
,使用
([^<>!]*)(<=>|[<>]=?|!?=)([^=>]*)
or, better yet in some cases, 或者,更好的是在某些情况下,
(\w+)(<=>|[<>]=?|!?=)(\w+)
The .*
is eating the !
.*
正在吃!
. 。 Make the
.*
specific to the operators you don't want it to match. 使
.*
特定于您不希望它匹配的运算符。 I think: 我认为:
([^!<>=]+)(<|>|<=|>=|!=|=)(.*)
Should do it. 应该这样做。
Demo: https://regex101.com/r/yM5aY8/1 演示: https : //regex101.com/r/yM5aY8/1
or if you are only work with numbers just use \\d+
. 或者如果您只使用数字,只需使用
\\d+
。
Demo2: https://regex101.com/r/yM5aY8/2 演示2: https : //regex101.com/r/yM5aY8/2
如果表达式的两边都有数字/变量名,那么在开头和结尾只使用。*而不是'\\ w。*'
(\w.*)(<|>|<=|>=|=|!=)(\w.*)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.