Java正则表达式在特定字符串之后捕获字符串 [英] Java Regex Capture String After Specific String

查看:502
本文介绍了Java正则表达式在特定字符串之后捕获字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在

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

没有空格

我有一个可正常使用的正则表达式,后来发现Java不支持\ K.

I got a working regex and later find out that java does not support \K.

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

有什么方法可以获得对\ K的支持?
还是其他正则表达式?
任何帮助将非常感激.

Is there any way to get support for \K?
or a different regex?
Any help would be much appreciated.

推荐答案

有什么方法可以获得对\ K的支持?

Is there any way to get support for \K?

可以想象,您可以使用提供它的第三方正则表达式库.您无法在标准库的 Pattern 类中获得它.

You could conceivably use a third-party regex library that provides it. You cannot get it in the standard library's Pattern class.

或其他正则表达式?

or a different regex?

我不确定您是否认识到捕获"是正则表达式领域中直接涉及该问题的技术术语.确实,这是处理您所描述内容的常用方法,但是您呈现的正则表达式根本不进行任何捕获.要使用Java正则表达式捕获所需的文本,您需要在模式中要捕获其匹配项的部分周围加上括号:

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:

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

如果匹配成功,则可以通过 Matcher group()方法访问捕获的组:

In case of a successful match, you access the captured group via the Matcher's group() method:

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);
    // ...
}

请注意,您需要对该正则表达式使用 matcher.find(),而不是 matcher.matches(),因为后者会测试整个字符串是否匹配,反之前者仅测试是否有匹配的子字符串.

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.

这篇关于Java正则表达式在特定字符串之后捕获字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆