基于和/或在搜索概念中的正则表达式中断字符串 [英] Regex break string based on and/or in a search concept
本文介绍了基于和/或在搜索概念中的正则表达式中断字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建正则表达式,但遇到了问题.
Hi I am trying to create regex expression and I am running into problems.
基本上这就是我所拥有的:
Basically this is what I have:
(.+?)(and|or)(.+?)
我要寻找的例子:
(user email ends with "@email.com" and user name is "John") or (user email ends with "@domain.com" and user name is "Bob")
我希望得到的预期结果是:
And my expected result that I would like to have is:
(user email ends with "@email.com" and user name is "John")
(user email ends with "@domain.com" and user name is "Bob")
基本上,OR会基于可选的()"进行拆分,因此我可以得到类似的东西
Basically the OR will split based on the "()" which is optional so I can have something like this
user email ends with "@email.com" and user name is "John"
我希望这样:
user email ends with "@email.com"
user name is "John"
如果我必须拥有一个以上的正则表达式,那么上面的最终目标是这样的:
if I have to have more than one regex I'm find with that, The end goal is something like this for the above:
Array
(
[0] => Array
(
[0] => user email ends with "@email.com"
[1] => user name is "John"
)
[1] => Array
(
[0] => user email ends with "@domain.com"
[1] => user name is "Bob"
)
)
如果是这样
(user email ends with "@email.com" and user name is "John") or ((user email ends with "@domain.com" and user name is "Bob") or (user id is 5))
然后我希望这样的事情
Array
(
[0] => Array
(
[0] => user email ends with "@email.com"
[1] => user name is "John"
)
[1] => Array
(
[0] => user email ends with "@domain.com"
[1] => user name is "Bob"
[2] => Array
(
[0] => user id is 5
)
)
)
任何帮助将不胜感激!
推荐答案
这是一个递归函数,它也使用递归正则表达式,让我们递归!
Here's a recursive function which also uses a recursive regex, let's recurse!!!
$text = '(user email ends with "@email.com" and user name is "John") or ((user email ends with "@domain.com" and user name is "Bob") or (user id is 5))';
print_r(buildtree($text));
function buildtree($input){
$regex = <<<'regex'
~( # Group 1
\( # Opening bracket
( # Group 2
(?: # Non-capturing group
[^()] # Match anything except opening or closing parentheses
| # Or
(?1) # Repeat Group 1
)* # Repeat the non-capturing group zero or more times
) # End of group 2
\) # Closing bracket
)~x
regex;
// The x modifier is for this nice and fancy spacing/formatting
$output = [];
if(preg_match_all($regex, $input, $m)){ // If there is a match
foreach($m[2] as $expression){ // We loop through it
$output[] = buildtree($expression); // And build the tree, recursive !!!
}
return $output;
}else{ // If there is no match, we just split
return preg_split('~\s*(?:or|and)\s*~i', $input);
}
}
输出:
Array
(
[0] => Array
(
[0] => user email ends with "@email.com"
[1] => user name is "John"
)
[1] => Array
(
[0] => Array
(
[0] => user email ends with "@domain.com"
[1] => user name is "Bob"
)
[1] => Array
(
[0] => user id is 5
)
)
)
这篇关于基于和/或在搜索概念中的正则表达式中断字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文