Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to match substring after nth occurence of pipe character

Tags:

java

regex

i am trying to build one regex expression for the below sample text in which i need to replace the bold text. So far i could achieve this much ((\|)).*(\|) which is selecting the whole string between the first and last pip char. i am bound to use apache or java regex.

Sample String: where text length between pipes may vary

1.1|ProvCM|111111111111|**10.15.194.25**|10.100.10.3|10.100.10.1|docsis3.0
like image 455
Ramesh Avatar asked May 13 '15 08:05

Ramesh


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

How do you escape a pipe in regex Java?

quote() method is used to escape the given regex pattern and transform it into a String literal. In other words, it escapes all the metacharacters present in the regex pattern for us.

What does *? Do in regex?

. *? is non-greedy. * will match nothing, but then will try to match extra characters until it matches 1 , eventually matching 101 . All quantifiers have a non-greedy mode: .


2 Answers

To match part after nth occurrence of pipe you can use this regex:

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

Here n=3

It will match 10.15.194.25 in matched group #1

RegEx Demo

like image 56
anubhava Avatar answered Oct 21 '22 17:10

anubhava


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

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

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

This here captures from start of string to | and then captures 3 such groups and stores it in $1.The next part of string till | is what you want.Now you can replace it with anything by $1<textyouwant>.

like image 43
vks Avatar answered Oct 21 '22 15:10

vks