简体   繁体   English

php“preg_match”中字符串的组正则表达式模式匹配

[英]group regex pattern matching of a string in php "preg_match"

I have a string我有一个字符串

(A) fdkf djkf gsdfjkg hsfl (B) jfg dkfjg hdksfjg dkfj (c) ndfkj gndfg ndfn (d) kdjfskdj fs;s dknls (A) fdkf djkf gsdfjkg hsfl (B) jfg dkfjg hdksfjg dkfj (c) ndfkj gndfg ndfn (d) kdjfskdj fs;s dknls

Desired output shuld be like this期望的输出应该是这样的

4 group matched
(A) fdkf djkf gsdfjkg hsfl
(B) jfg dkfjg hdksfjg dkfj
(c) ndfkj gndfg ndfn
(d) kdjfskdj fs;s dknls

Please help请帮忙

I am trying /((.+?) (?=\\())/ regex but it is not creating 4 groups我正在尝试/((.+?) (?=\\())/ regex 但它没有创建 4 个组

I am trying here to create this pattern https://regex101.com/r/KxAcaV/1我在这里尝试创建此模式https://regex101.com/r/KxAcaV/1

$re = '/((.+?) (?=\())/';
$str = '(A) fdkf djkf gsdfjkg hsfl (B) jfg dkfjg hdksfjg dkfj (c) ndfkj gndfg ndfn  (d) kdjfskdj fs;s dknls';

preg_match($re, $str, $matches, PREG_OFFSET_CAPTURE, 0);

// Print the entire match result
var_dump($matches);

Use preg_match_all :使用preg_match_all

$str = '(A) fdkf djkf gsdfjkg hsfl (B) jfg dkfjg hdksfjg dkfj (c) ndfkj gndfg ndfn (d) kdjfskdj fs;s dknls';

preg_match_all('/\(.+?\).+?(?= \(|$)/', $str, $m);
print_r($m[0]);

Output:输出:

Array
(
    [0] => (A) fdkf djkf gsdfjkg hsfl
    [1] => (B) jfg dkfjg hdksfjg dkfj
    [2] => (c) ndfkj gndfg ndfn
    [3] => (d) kdjfskdj fs;s dknls
)

If your string always has 4 groups, then you can use a pattern matching a symbol in parenthesis followed by some text repated 4 times:如果您的字符串总是有 4 个组,那么您可以使用匹配括号中符号的模式,然后是一些重复 4 次的文本:

^(\(.\).+?)\s+(\(.\).+?)\s+(\(.\).+?)\s+(\(.\).+?)$

But if your string has a variable number of groups, then you can't get them all inside different matched groups, you'll need to get them with preg_match_all :但是,如果您的字符串具有可变数量的组,那么您无法将它们全部放入不同的匹配组中,您需要使用preg_match_all获取它们:

(\(.\)[^(]+)

Demo here .演示在这里

It's easiest to split your string with the regex用正则表达式拆分字符串是最简单的

(?i) +(?=\([a-z]\))

which matches one or more spaces followed by a left parenthesis followed by a letter followed by a right parenthesis, (?=\\([az]\\)) being a positive lookahead .它匹配一个或多个空格,后跟一个左括号,后跟一个字母,后跟一个右括号, (?=\\([az]\\))是一个积极的前瞻

demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM