Reputation: 832
I'd like to get the single strings of a pipe-separated string, with "pipe escaping" support, e.g.:
fielda|field b |field\|with\|pipe\|inside
would get me:
array("fielda", "field b ", "field|with|pipe|inside")
How would I reach that goal with a regular expression?
Upvotes: 3
Views: 11468
Reputation: 626748
You may match these items with
(?:[^\\|]|\\[\s\S])+
See the regex demo.
NOTE: If you need to split on a character other than |
just replace it within the first negated character class, [^\\|]
. Just note that you will have to escape ]
(unless it is placed right after [^
) and -
(if not at the start/end of the class).
The [\s\S]
can be replaced with a .
in many engines and pass the appropriate option to make it match across line endings.
See the regex graph:
JS demo:
console.log(
"fielda|field b |field\\|with\\|pipe\\|inside".match(/(?:[^\\|]|\\[\s\S])+/g)
)
// => ["fielda", "field b ", "field\|with\|pipe\|inside"]
Upvotes: 0
Reputation: 89547
An other way with php, using strtr
that replace \|
with a placeholder:
$str = 'field a|field b|field\|with\|pipe\|inside';
$str = strtr($str, array('\|' => '#'));
$result = array_map(function ($i) {
return strtr($i, '#', '|');
}, explode('|', $str));
Upvotes: 0
Reputation: 4953
This should work too:
((?:[^\\|]+|\\\|?)+)
The regex will capture everything up to a single |
(including \|
)
Upvotes: 1
Reputation: 67968
Split by this (?<!\\)\|
See demo.The lookbehind makes sure |
is not after \
.
https://regex101.com/r/pM9yO9/15
Upvotes: 7