java 正则提取,使用正则表达式在Java中提取值

这篇博客介绍了如何使用Java的Pattern和Matcher类来从字符串中提取以特定格式存在的数字。作者提供了一个全例子,展示了如何通过正则表达式`^D+(d+).*`找到并获取字符串中的第一个数字,例如在`Testing123Testing`中提取出`123`。代码示例中,`m.group(1)`将返回找到的第一个数字。
部署运行你感兴趣的模型镜像

I have several strings in the rough form:

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

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

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].

EDIT: 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].

解决方案

Full example:

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+).*

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

^\D+(-?\d+).*

您可能感兴趣的与本文相关的镜像

Wan2.2-T2V-A5B

Wan2.2-T2V-A5B

文生视频
Wan2.2

Wan2.2是由通义万相开源高效文本到视频生成模型,是有​50亿参数的轻量级视频生成模型,专为快速内容创作优化。支持480P视频生成,具备优秀的时序连贯性和运动推理能力

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值