java匹配特定字符串和位数,Java REGEX匹配字符串中的确切位数

I tried to find the answer to my problem in the questions history but they just come back in more than one thousand and after scanning through a few tens of matching answers I gave up.

So here is my problem.

I want to be able to find the first sequence of exactly six digits in a string.

Given the string

“Some text 987654321 and some more text 123456 and some other text again 654321 and more text in the end”

I want to find the regex that will match the 123456 sequence.

I am new to regex and a short explanation about how it works will help a lot.

Thank you in advance

解决方案

You can use the pattern (?

That could look like this:

final String number;

{

final Matcher m = Pattern.compile("(?

if(m.find())

number = m.group(); // retrieve the matched substring

else

number = null; // no match found

}

Note: a previous version of this answer suggested the use of word boundaries, \b; but one of your comments suggests that the digits might be immediately preceded or followed by Traditional Chinese characters, which are considered word characters (and therefore wouldn't trigger a word boundary), so I've changed that.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值