JC3358227
JC3358227

Reputation: 21

How to pull the first four consecutive digits in an alphanumeric string?

I have a string which contains alphanumeric characters- this is a serial number of a product. I need a way to pull the first four consecutive digits in that string, these represent the manufactured date of the product in YYMM.

Example string: USA43XY121100004. 1211 is what I would need.

Thanks

Upvotes: 2

Views: 384

Answers (1)

Szymon
Szymon

Reputation: 43023

You can use regular expressions and find the first group of 4 digits:

Pattern p = Pattern.compile("([0-9]{4})");
Matcher m = p.matcher("USA43XY121100004");

if (m.find()) {
    System.out.println(m.group(1));
}

As suggested in the comments, a version without group capturing in the regex:

Pattern p = Pattern.compile("[0-9]{4}");
Matcher m = p.matcher("USA43XY121100004");

if (m.find()) {
    System.out.println(m.group());
}

Upvotes: 5

Related Questions