Search code examples
regexapache-nifireplaceall

Regular expression to match pipes with no sub-string between them


Can somebody please share the regex to match only the Pipes with no sub string between them?

For example:

ABC, XYZ, |||,|||||, ||G|F|,1|2,||||, R|T|Y

I only want ||| and ||||| and |||| selected.

Thanks in advance for your help.

Edit:

Using the help of people in the comments below. I have a regex that partially works (?<=^|,\s)?(\|+)(?=,|,$)

However, this selects the | after F in sub string ||G|F|

Is there anyway to modify this regex to only select pipes between commas that do not have strings between them?


Solution

  • You haven't given the language you are using. If it supports \K, as does PCRE (PHP) and others, you extract substrings that match the following regular expression.

    (?:^|,)[^,|]*\K\|{2,}(?=[^,|]*(?:,|$))
    

    Demo

    The regex engine performs the following operations.

    (?:^|,)     # match start of string or ',' in a non-capture group
    [^,|]*      # match 0+ chars other than ',' and '|'
    \K          # forget everything matched so far
    \|{2,}      # match 2+ '|'  
    (?=
      [^,|]*    # match 0+ chars other than ',' and '|'
      (?:,|$)   # match a comma or the end of the string 
    )           # end non-capture group 
    

    Taken from the demo link, "\K resets the starting point of the reported match."

    If you wish to match single pipes between commas (e.g, ,1|2,) change {2,} to +.

    If \K is not supported but a capture group could be used the following regular expression could be used.

    (?:^|,)[^,|]*(\|{2,})(?=[^,|]*(?:,|$))
    

    Demo

    The strings of interest are held in capture group 1 for each match.