java 正则表达式在第 n 次出现管道字符后匹配子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30210118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:40:07  来源:igfitidea点击:

regex to match substring after nth occurence of pipe character

javaregex

提问by Ramesh

i am trying to build one regex expression for the below sample text in which i need to replace the boldtext. 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.

我正在尝试为下面的示例文本构建一个正则表达式,我需要在其中替换粗体文本。到目前为止,我可以做到这一点 ((\|)).*(\|),即选择第一个和最后一个 pip 字符之间的整个字符串。我一定会使用 apache 或 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

回答by anubhava

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

要在nth管道出现后匹配部分,您可以使用此正则表达式:

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

Here n=3

这里 n=3

It will match 10.15.194.25in matched group #1

它将10.15.194.25在匹配组 #1 中匹配

RegEx Demo

正则表达式演示

回答by vks

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

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

您可以使用 this.Replace by $1<anything>.See 演示。

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

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

This here captures from startof 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>.

这在这里捕获 from startof string to|然后捕获 3 个这样的组并将其存储在.The $1next part of string until|是你想要的。现在你可以用任何东西替换它$1<textyouwant>

回答by Denys Séguret

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+"})[^|]+", ""+newValue);

This builds:

这构建:

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