Chris2011931
Chris2011931

Reputation: 106

Replace nth occurence in a string between two characters

i have to use regular expressions to cross out some content in a string.

For example
SomeText;content1|content2|content3|||content6||content8

As you can see, the contents are separated by pipes. Contents do not have a fixed length and can consist of any characters. Now I want to replace content6 by xxxxxx. Therefore I need something like "replace the content between the pipes on occurence number 6"

Result should be: SomeText;content1|content2|content3|||xxxxxx||content8

Does anyone have an idea how to do this? Thank you in advance!

Upvotes: 0

Views: 361

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

Assuming that there won't be any "escaped pipes" we need to deal with, you could search for

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

and replace that with \1xxxxxx\2.

Test it live on regex101.com.

Explanation:

[^|]* matches any number of characters besides |, so (?:[^|]*\|){5} matches everything up to and including the 5th pipe.

Upvotes: 1

Related Questions