0

This is not a duplicate. I have checked before asking.

I have this string separated with | and I want to match the nth element.

aaaaaaaaa aaa|bb bbbbb|cccc ccccccc|ddd ddddddd|aaa aaa aaaaa|zzz zzz zzzzzzz

The closer I got is using this pattern but it buggy:

([^\|]*\|){2}[^\|]*

https://regex101.com/r/EYZbK5/1

This is plain pcre. In this context, javascript such .split() cannot be used.

Say I want to get the 3rd element cccc ccccccc what regex should I use?

Azevedo
  • 2,059
  • 6
  • 34
  • 52
  • This seems to be an exact duplicate. Please see the marked question and if it didn't provide you an answer then edit accordingly. – revo Sep 20 '18 at 18:30
  • Well, the accepted answer really suggests using a capturing group. Since the answer accepted suggest the same solution, it is really a dupe, as you are not interested in PCRE specific options. – Wiktor Stribiżew Sep 21 '18 at 08:21

3 Answers3

4

You may use

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

See the regex demo.

Details

To avoid empty string matches, you may replace the last [^|]* with [^|]+.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
4

You could use an anchor to assert the start of the line and then repeat not matching a | followed by a | 2 times. Then capture the third part in a capturing group which will contain cccc ccccccc

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

Regex demo

Explanation

  • ^ Assert the start of the line
  • (?: Start non capturing group
    • [^|]*\| Match not a | using a negated character class zero or more times followed by a |.
  • ){2} close non capturing group and repeat that 2 times
  • ([^|]*) Capture in a group matching not a | zero or more times
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
2

you may try this and take group2

(\|?(.*?)(?:\|)){3}

demo and explanation

The Scientific Method
  • 2,374
  • 2
  • 14
  • 25