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.