正则表达式提取foo,bar,baz和逻辑运算符

时间:2022-05-31 22:29:11

String Parsing

字符串解析

foo_and_bar_and_baz_or_doe

expected result: foo, bar, baz and doe along with and, and and or.

预期结果:foo,bar,baz和doe以及和,和和。

i tried /(.*?)(_and_|_or_)/i but its skipping last one.

我试过/(.*?)(_and_|_or_)/i但跳过最后一个。

actually sting is

实际上是刺痛的

having_tag_slugs_and_having_category1_slug_and_having_category2_slug_or_having_category3_slug

out put, i am looking is

out put,我看的是

having_tag_slugs
having_category1_slug
having_category2_slug
having_category3_slug

_and_
_and_
_or_
''

3 个解决方案

#1


1  

You can try the following regular expression -

您可以尝试以下正则表达式 -

/(.*?)(_and_|_or_|$)/im

Hope that helps. Let me know how it goes :)

希望有所帮助。让我知道事情的后续 :)

#2


1  

$a="foo_and_bar_and_baz_or_doe";
$c=explode("_",$a);
print_r($c);

#3


1  

How about preg_split:

preg_split怎么样:

$str = 'having_tag_slugs_and_having_category1_slug_and_having_category2_slug_or_having_category3_slug';
$arr = preg_split('/(_and_|_or_)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($arr);

output:

输出:

Array
(
    [0] => having_tag_slugs
    [1] => _and_
    [2] => having_category1_slug
    [3] => _and_
    [4] => having_category2_slug
    [5] => _or_
    [6] => having_category3_slug
)

#1


1  

You can try the following regular expression -

您可以尝试以下正则表达式 -

/(.*?)(_and_|_or_|$)/im

Hope that helps. Let me know how it goes :)

希望有所帮助。让我知道事情的后续 :)

#2


1  

$a="foo_and_bar_and_baz_or_doe";
$c=explode("_",$a);
print_r($c);

#3


1  

How about preg_split:

preg_split怎么样:

$str = 'having_tag_slugs_and_having_category1_slug_and_having_category2_slug_or_having_category3_slug';
$arr = preg_split('/(_and_|_or_)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($arr);

output:

输出:

Array
(
    [0] => having_tag_slugs
    [1] => _and_
    [2] => having_category1_slug
    [3] => _and_
    [4] => having_category2_slug
    [5] => _or_
    [6] => having_category3_slug
)