tags:

views:

123

answers:

3

I have a string which could contain multiple delimiters right next to each other, for example |||, although it could be any number of adjacent delimiters. I need to replace any place "in between" the adjacent pair with a specific character. These delimiters will only need to match if there is no character between the delimiter, not even spaces.

So Replace:

ABC|||Blah     with     ABC|*|*|Blah

However, when I try it, it will not "fill in" the gap between all of them. In the same example above it only results in ABC|*||Blah
Four delimiters result in ABC|*||*|Blah

How do I write a regex pattern that will do what I need? I am using php's preg_replace.

+1  A: 

Using both look-ahead and look-behind:

(?<=\|)(?=\|)

replace globally with

*
Tomalak
All you'd have to is PHP escaping the regex string for use with preg_replace().
Tomalak
A: 

Why not working with str_replace:

$str = str_repalce('||', '|*|', str_replace('||', '|*|', $str));


Edit   As I think I know understand what you are looking for, there are three cases the gaps can occur:

  1. at the start: |foo|bar*|foo|bar
  2. in the middle: foo||barfoo|*|bar
  3. at the end: foo|bar|foo|bar|*

The latter two can be handled at once, but the first has to be handled separatly:

$str = preg_replace('/^\|/', '*|', preg_replace('/\|(?=\||$)/', '|*', $str))
Gumbo
So why not str_replace, Mr. Down-vote?
Gumbo
I agree. No need to use a sledgehammer to kill a fly.
razzed
@Gumbo: I did not vote you down, but to answer your question: its simple, you didn't provide an answer to his question. If someone wants to know how to do with Regex, then tell him, or let it be.
BeowulfOF
@BeowulfOF: So when someone asks for a regex to parse HTML, it’s better to give him an enormous regex that will probably fail than to tell him to use a real parser, just because he asked for a regex?
Gumbo
+1  A: 

The answer that worked for me turned out to be a positive lookahead.

/\|(?=\|)/

This matched all places where the delimiters were strictly adjacent. That the second delimiter, in the forward lookahead, was not considered as part of the match was the key to allow me to match them in the example mentioned.

tribule