-2

So I'm looking at a string like this with a | delimiter:

XL231241424|AB|ABCDE|LK|Word|A Phrase|Another random phrase|GH49|Example|31/02/2020|05/03/2020|N/A|N/A|N/A

The end goal is to pluck specific items from this string and concatenate them together, essentially giving a more concise bit of text for readable in a reporting platform.

I tried this and this but couldn't get it to work for my string. The match is simple, it's just: ([^\|]*) but how do I then just pull a match in position x? Specifically, if I want to get Another random phrase which is position 7, how do I do that?

Any help is much appreciated and an explanation is even better!

Thanks.

  • 1
    u tried with which programming language? – GolamMazid Sajib Apr 16 '20 at 18:04
  • 1
    [This link](https://stackoverflow.com/questions/48914235) shows you how to do that – Wiktor Stribiżew Apr 16 '20 at 18:46
  • @Jan, I don't think this question warrants closure. The earlier question you cite is different (and more complex), as it seeks the nth substring that has a particular property; this question merely requires that pipes be counted. Moreover, even if a solution to the earlier question could be applied here I was unable to find any that were correct. I therefore request that you reverse your closing of this question. – Cary Swoveland Apr 17 '20 at 21:21
  • @CarySwoveland: Well then, go for it. – Jan Apr 18 '20 at 11:03
  • Another dupe - [regex to match substring after nth occurence of pipe character](https://stackoverflow.com/questions/30210118/regex-to-match-substring-after-nth-occurence-of-pipe-character). – Wiktor Stribiżew Apr 18 '20 at 11:23
  • @WiktorStribiżew, in my comment to Jan, I meant that I didn’t think this question warranted closure based on the earlier question he cited. You have shown it to be a dup, however, and I certainly have no problem with that. – Cary Swoveland Apr 18 '20 at 12:25

1 Answers1

0

You could use

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

Demo

In your example Another random phrase would be saved to capture group 1.

The regex engine performs the following operations.

^          # match beginning of line
(?:        # begin a non-capture group
  [^|]*\|  # match 0+ chars other than '|' followed by '|'
)          # end non-capture group
{6}        # execute non-capture group 6 times
([^|]*)    # match 0+ chars other than '|' in capture group 1

If your regex engine supports \K (as does PCRE (PHP), P and others), you don't need a capture group:

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

Demo

In your example this matches Another random phrase.

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

The regex engine performs the following operations.

^          # match beginning of line
(?:        # begin a non-capture group
  [^|]*\|  # match 0+ chars other than '|' followed by '|'
)          # end non-capture group
{6}        # execute non-capture group 6 times
\K         # discard everything matched so far
[^|]*      # match 0+ chars other than '|'
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100