Regex to extract nth token of a string separated by pipes

前端 未结 2 1455
执笔经年
执笔经年 2021-01-24 15:16

I\'m new in Regex

I need to count and extract tokens from the below sample text:

AA||CCCCCCCC|||FFFFFFFFFFF

Requesting 4th token I mus

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-24 15:50

    Splitting the string on | would be more effective, but this works too.

    Code

    We'll call the counter the number between curly brackets {X}. That counter begins at 0. If it's set to 0, we'll get the 1st element, if it's set to 5, we'll get the 6th element, etc.

    See regex in use here

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

    Alternatively, if \K isn't supported in your regex engine, you can use the following (result in the first capture group):

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

    Explanation

    • ^ Assert position at the start of the line
    • (?:[^|]*\|){5} Match the following exactly 5 times
      • [^|]* Match any character except | any number of times
      • \| Match | literally
    • \K Resets the starting point of the match. Any previously consumed characters are no longer included in the final match
    • [^|]* Match any character except | any number of times

提交回复
热议问题