0

Suppose I have an arbitrary string combined with 'a' and 'b':

ab
aba
ababa
aaabbbaaabaaaaaab

I'd like to insert '|' between every pair of 'ab' or 'ba', for example:

ab -> a|b
aba -> a|b|a
ababa -> a|b|a|b|a
aaabbbaaabaaaaaab -> aaa|bbb|aaa|b|aaaaaa|b

Is there possible a regular expression to capture all the group?

MDK. dc
  • 121
  • 1
  • 6

1 Answers1

1

You can replace each match of the regular expression

(?<=a)(?=b)|(?<=b)(?=a)

with '|'.

Demo

(?<=a) is a positive lookbehind, asserting that the match is preceded (immediately) by 'a'. Similarly, (?<=b) asserts that the match is preceded by 'b'.

(?=b) is a positive lookahead, asserting that the match is followed (immediately) by 'b'. Similarly, (?<=a) asserts that the match is followed 'a'.

The matches are empty strings between adjacent letters, often referred to as zero-width matches.

One may alternatively use the regular expression

(?<=(.))(?!\1)

(?!\1) being a negative lookahead.

Cary Swoveland
  • 94,081
  • 5
  • 54
  • 87
  • 1
    Hey Cary, I found it doesn't work in Safari, is there an alternative expression in Safari? – MDK. dc Jun 10 '20 at 10:15
  • I don't know, as I'm not familiar with Safari's regex engine. I wouldn't have answered had Safari been mentioned if the question. – Cary Swoveland Jun 14 '20 at 03:09