在 Java 中使用正则表达式提取值 [英] Using Regular Expressions to Extract a Value in Java

查看:68
本文介绍了在 Java 中使用正则表达式提取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个粗略的字符串:

I have several strings in the rough form:

[some text] [some number] [some more text]

我想使用 Java Regex 类提取 [some number] 中的文本.

I want to extract the text in [some number] using the Java Regex classes.

我大致知道我想使用什么正则表达式(尽管欢迎提出所有建议).我真正感兴趣的是 Java 调用以获取正则表达式字符串并将其用于源数据以生成 [某个数字] 的值.

I know roughly what regular expression I want to use (though all suggestions are welcome). What I'm really interested in are the Java calls to take the regex string and use it on the source data to produce the value of [some number].

我应该补充一点,我只对一个[某个数字](基本上是第一个实例)感兴趣.源字符串很短,我不会寻找多次出现的 [some number].

I should add that I'm only interested in a single [some number] (basically, the first instance). The source strings are short and I'm not going to be looking for multiple occurrences of [some number].

推荐答案

完整示例:

private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
    // create matcher for pattern p and given string
    Matcher m = p.matcher("Testing123Testing");

    // if an occurrence if a pattern was found in a given string...
    if (m.find()) {
        // ...then you can use group() methods.
        System.out.println(m.group(0)); // whole matched expression
        System.out.println(m.group(1)); // first expression from round brackets (Testing)
        System.out.println(m.group(2)); // second one (123)
        System.out.println(m.group(3)); // third one (Testing)
    }
}

由于您正在寻找第一个数字,您可以使用这样的正则表达式:

Since you're looking for the first number, you can use such regexp:

^D+(d+).*

m.group(1) 将返回您的第一个数字.请注意,有符号数可以包含减号:

and m.group(1) will return you the first number. Note that signed numbers can contain a minus sign:

^D+(-?d+).*

这篇关于在 Java 中使用正则表达式提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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