简体   繁体   English

具有匹配文本和特殊字符的 Java 正则表达式

[英]Java regular expression with Matching text and special charachter

Hi I am new to java regex.您好,我是 Java 正则表达式的新手。 I have the below string我有以下字符串

String s = " "KBC_2022-12-20-2004_IDEAL333_MASTER333_2022-12-20-1804_SUCCESS";

I wanted to only Print "333" which is appended with MASTER.我只想打印附加了 MASTER 的“333”。 The output should be 333. Can someone help me writing the regex for this.输出应为 333。有人可以帮我为此编写正则表达式吗? Basically the code should print the value between "MASTER" and the next "_".基本上代码应该打印“MASTER”和下一个“_”之间的值。 here its 333 but the value might be of any number of character not limit to length 3.这里是 333,但该值可以是任意数量的字符,不限于长度 3。

You can use this regex: (?<=MASTER)[0-9]+(?=\_) .您可以使用此正则表达式: (?<=MASTER)[0-9]+(?=\_)

We are looking for everything between MASTER and _ :我们正在寻找MASTER_之间的所有内容:

  • lookbehind : everything that goes after MASTER : (?<=MASTER)回顾MASTER之后的所有内容: (?<=MASTER)
  • lookahead : everything that goes before _ : (?=\_)前瞻:在_之前发生的一切: (?=\_)

Try on regex101.comregex101.com上试试

You can do MASTER(\\d+)_你可以做MASTER(\\d+)_

Pattern p = Pattern.compile("MASTER(\\d+)_");
Matcher m = p.matcher(" KBC_2022-12-20-2004_IDEAL333_MASTER333_2022-12-20-1804_SUCCESS");
if (m.find()) {
    System.out.println(m.group(1)); // 333
}
m = p.matcher(" KBC_2022-12-20-2004_IDEAL333_MASTER123_2022-12-20-1804_SUCCESS");
if (m.find()) {
    System.out.println(m.group(1)); // 123
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM