简体   繁体   English

Java正则表达式在特定字符串之后捕获字符串

[英]Java Regex Capture String After Specific String

I need to capture the "456456" in 我需要捕获“ 456456”中的

Status: Created | Ref ID: 456456 | Name: dfg  | Address: 123

with no whitespaces 没有空格

I got a working regex and later find out that java does not support \\K. 我有一个可运行的正则表达式,后来发现Java不支持\\ K。

\bRef ID:\s+\K\S+

Is there any way to get support for \\K? 有什么方法可以获得对\\ K的支持?
or a different regex? 或其他正则表达式?
Any help would be much appreciated. 任何帮助将非常感激。

Is there any way to get support for \\K? 有什么方法可以获得对\\ K的支持?

You could conceivably use a third-party regex library that provides it. 可以想象,可以使用提供它的第三方正则表达式库。 You cannot get it in the standard library's Pattern class. 您不能在标准库的Pattern类中获得它。

or a different regex? 或其他正则表达式?

I'm uncertain whether you recognize that "capture" is a technical term in the regex space that bears directly on the question. 我不确定您是否认识到“捕获”是正则表达式领域中直接涉及这个问题的技术术语。 It is indeed the usual way to go about what you describe, but the regex you present doesn't do any capturing at all. 确实,这是处理您所描述内容的常用方法,但是您呈现的正则表达式根本不进行任何捕获。 To capture the desired text with a Java regex, you want to put parentheses into the pattern, around the part whose match you want to capture: 要使用Java正则表达式捕获所需的文本,您需要在模式中要捕获其匹配项的部分周围加上括号:

\bRef ID:\s+(\S+)

In case of a successful match, you access the captured group via the Matcher 's group() method: 如果匹配成功,则可以通过Matchergroup()方法访问捕获的组:

String s = "Status: Created | Ref ID: 456456 | Name: dfg  | Address: 123";
Pattern pattern = Pattern.compile("\\bRef ID:\\s+(\\S+)");
Matcher matcher = pattern.matcher(s);

if (matcher.find()) {
    String refId = matcher.group(1);
    // ...
}

Note that you need to use matcher.find() with that regex, not matcher.matches() , because the latter tests whether the whole string matches, whereas the former tests only whether there is a substring that matches. 请注意,您需要在该正则表达式中使用matcher.find() ,而不是matcher.matches() ,因为后者测试整个字符串是否匹配,而前者仅测试是否存在匹配的子字符串。

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

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