Regular expression to match a substring after the nth occurrence of a pipe character

I am trying to create one regular expression expression for the sample text below in which I need to replace the text with bold . So far I could achieve this ((\|)).*(\|) , Which selects the entire line between the first and last pip char. I have to use apache or java regular expressions.

Example line: where the length of text between pipes can vary

 1.1|ProvCM|111111111111|**10.15.194.25**|10.100.10.3|10.100.10.1|docsis3.0 
+6
source share
3 answers

To match the part after the nth appearance of the channel, you can use this regex:

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

Here n = 3

It will correspond to 10.15.194.25 in the agreed group # 1

RegEx Demo

+11
source
 ^((?:[^|]*\\|){3})[^|]+ 

You can use this.Replace by $1<anything> Watch a demo.

https://regex101.com/r/tP7qE7/4

Here it is fixed from the start line to | , and then 3 such groups are captured and stored at $1 . The next part of the line before | - Is this what you want. Now you can replace it with anything $1<textyouwant> .

+3
source

Here you can make a replacement:

 String input = "1.1|ProvCM|111111111111|10.15.194.25|10.100.10.3|10.100.10.1|docsis3.0"; int n = 3; String newValue = "new value"; String output = input.replaceFirst("^((?:[^|]+\\|){"+n+"})[^|]+", "$1"+newValue); 

This assembly:

 "1.1|ProvCM|111111111111|new value|10.100.10.3|10.100.10.1|docsis3.0" 
0
source

Source: https://habr.com/ru/post/987113/


All Articles