regex to match substring after nth occurence of pipe character

前端 未结 3 945
有刺的猬
有刺的猬 2020-11-30 12:51

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 ((\\|))

相关标签:
3条回答
  • 2020-11-30 13:06
    ^((?:[^|]*\\|){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>.

    0 讨论(0)
  • 2020-11-30 13:28

    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

    0 讨论(0)
  • 2020-11-30 13:32

    Here's how you can do the 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 builds:

    "1.1|ProvCM|111111111111|new value|10.100.10.3|10.100.10.1|docsis3.0"
    
    0 讨论(0)
提交回复
热议问题