Home > Back-end >  Ignore pattern in split()
Ignore pattern in split()

Time:12-21

I want to Split a String delimited by '|'. But want to ignore a String value that has '|'. Find below example:

String s = "Shashank|Sam|Location|20246|India|City in India|USA Country|Location|India Specific 2021|25236|A";

I want to consider Location|India Specific 2021 as one value.

Expected Output:

Shashank
Sam
Location
20246
India
City in India
USA Country
Location|India Specific 2021
25236
A

Whenever I find Location|India in String, I want to ignore | in that.

I tried using

(?<!Location|India)\|

But output is

Shashank
Sam
Location|20246
India
City in India
USA Country
Location|India Specific 2021
25236
A

Thanks

CodePudding user response:

You can use this regex with a negative lookahead with a nested lookbehind:

\|(?!(?<=Location\|)India )

RegEx Demo

RegEx Details:

  • \|: Match a |
  • (?!: Start negative lookahead
    • (?<=Location\|): Make sure that we have Location| before current position
    • India : Match India
  • ): End negative lookahead

CodePudding user response:

(?<!\bLocation)\||\|(?!India\b)

Demo

This regular expression matches a pipe character (\|) that is not preceded by 'Location' or (|) a pipe character that is not followed by 'India'. (?<!\bLocation) is a negative lookbehind; (?!India\b) is a negative lookahead.

The word boundary (\b) following 'India' is to permit a match of '|' in (for example) 'Location|Indiana' (similar for the word boundary before 'Location').

  • Related