我有一些以字符串形式出现的数据,我需要提取或打印出 月值 (中间组)形式为:
[项目值] [月值] [年值]
规则是:
项目值(value) = 长度可以是 1-3 个字符(或数字)
月值 = 是单个字母字符 [a-z]
年值 = 可以是代表日历年的 1、2 或 4 位数字
一些示例输入:
输入1 AP18
输出1 P
输入2 QZAB19
输出2 B
输入3 ARM8
输出3 M
我试图 编译一个 图案像:
Pattern pattern = Pattern.compile("([a-zA-Z0-9]{1,3})([a-z])([0-9]{1,4})");
然后调用匹配器 输入到 查找() 组,在本例中为 月值 ,应该是 matcher.group(2) 像:
Matcher m = pattern.matcher("OneOfTheExampleInputStringsFromAbove");
if (matcher.find()) {
System.out.println(matcher.group(2));
}
我以为我已经接近了,但一个问题是如何包含 1、2 和 4 的长度,但不包括 的 3 长度年值 .我的方法好吗?我在编译模式中遗漏了什么吗?
请告诉我!
最佳答案
你的正则表达式是正确的。要添加您的最后一个要求,您可以尝试:
^\w{1,3}([a-zA-Z])(?:\d{1,2}|\d{4})$
^^^^^^^^^^^^^^^^
This part
上述正则表达式的解释:
^, $
- Represents start and end of line respectively.
\w{1,3}
- Matches from[0-9A-Za-z_]
1 to 3 times. If there is a chance that your test string contains_
; then try to use[0-9A-Za-z]
here.
([a-zA-Z])
- Represents capturing group matching a letter.
(?:\d{1,2}|\d{4})
- Represents a non-capturing group matching the digits 1, 2 or 4 times but not three.
您可以在 here. 中找到上述正则表达式演示
java中的实现:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main
{
private static final Pattern pattern = Pattern.compile("^\\w{1,3}([a-zA-Z])(?:\\d{1,2}|\\d{4})$", Pattern.MULTILINE);
public static void main(String[] args) {
final String string = "QZAB19\n"
+ "AP18\n"
+ "ARM8\n"
+ "ARM803"; // This won't match since the year value is 3.
Matcher matcher = pattern.matcher(string);
while(matcher.find())System.out.println(matcher.group(1)); // 1st group matches the month-value.
}
}
您可以在 here. 中找到上述代码的示例运行。
关于Java正则表达式解析字符串的中间值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62255057/