How to split a string with a separator that is not preceded by a character?

Viewed 76

I have a string str = "Jake!!!Jackson!!!Tyson\\!!!!!!Pete"

I want to split the string by !!! but ignore it if the char before !!! is "\\".

I came up str.split("(?<!\\\\)!!!");

But the output is Jake,Jackson,Tyson\!,!!Pete and the expected output is Jake,Jackson,Tyson\!!!,Pete

Can this be accomplished by regex?

1 Answers

I think the following could work:

(?<!\\)!!!(?=(?:!!!)*(?!!))

See the online demo

  • (?<!\\) - Assert position not preceded by a literal backslash.
  • !!! - Literally three exclamation marks.
  • (?= - Open positive lookahead:
    • (?: - Open non-capture group:
      • !!! - Literally three exclamation marks.
      • )* - Close non-capture group and match 0+ times.
    • (?!!) - Negative lookahead for exclamation mark.
  • ) - Close positive lookahead.

This would split a string like Jake!!!Jackson!!!Tyson\!!!!!!!Pete including a NULL too (assuming that is what you are after). As a Java-string: "(?<!\\\\)!!!(?=(?:!!!)*(?!!))"

Related