2

Suppose I have a string like this in php(laravel):

make|aaa|select.aaa|ttt|actived_by(creator.url|test|ali)

Now I want to convert it to an array like this:

make
aaa
select.aaa
tttt
actived_by(creator.url|test|ali)

As you can see only pipe signs that are not included in brackets used to separation.

For that I wrote a function like this :

function parseQuery($query) {
    preg_match_all("/[^\|]+/", $query, $match);
    return $match;
}

But it has below output:

make
aaa
select.aaa
ttt
actived_by(creator.url
test
ali)

What is proper regex to use for desired result ?

thisiskelvin
  • 4,136
  • 1
  • 10
  • 17

2 Answers2

2

You can use the following regex instead:

(?=[^|])(?:[^|]*\([^)]+\))*[^|]*

Demo: https://regex101.com/r/CONoJ2/2

blhsing
  • 91,368
  • 6
  • 71
  • 106
2

Instead of splitting, it may also make sense to use preg_match_all using this regex:

/[^|(]+(\([^)]+\))?/

This will capture a string with no parenthesis or pipes [^(]+, optionally followed by a section encapsulated by parenthesis (\([^)]+\))?

The regex is demoed here in javascript

var input = "make|aaa|select.aaa|ttt|actived_by(creator.url|test|ali)"

console.log(input.match(/[^|(]+(\([^)]+\))?/g))
jmcgriz
  • 2,819
  • 1
  • 9
  • 11