简体   繁体   中英

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

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

I am trying here to create this pattern 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 :

$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:

^(\(.\).+?)\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 :

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

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 .

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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