如何在字母数字字符串中拉出前四个连续数字?

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

我有一个包含字母数字字符的字符串 - 这是产品的序列号。我需要一种方法来拉取该字符串中的前四个连续数字,这些数字代表YYMM中产品的制造日期。

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

示例字符串:USA43XY121100004。 1211是我需要的。

Thanks

谢谢

1 个解决方案

#1


5  

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

您可以使用正则表达式并查找第一组4位数:

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());
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/02/27/a81e66bbeff8b2ee618c69f766d3204.html



 
  © 2014-2022 ITdaan.com 联系我们: