gpt4 book ai didi

java - 删除多个正则表达式的交集?

转载 作者:搜寻专家 更新时间:2023-11-01 03:53:26 25 4
gpt4 key购买 nike

 Pattern[] a =new Pattern[2];
a[0] = Pattern.compile("[$£€]?\\s*\\d*[\\.]?[pP]?\\d*\\d");
a[1] = Pattern.compile("Rs[.]?\\s*[\\d,]*[.]?\\d*\\d");

例如:Rs.150a[1] 检测到和 150a[0] 检测到.如何删除此类交叉点并让它仅通过 a[1] 检测但不是 a[0]

最佳答案

您可以在正则表达式中使用 | 运算符。然后调用方法Matcher#group(int)查看您的输入适用于哪种模式。如果匹配组为空,此方法返回 null

示例代码

public static void main(String[] args) {
// Build regexp
final String MONEY_REGEX = "[$£€]?\\s*\\d*[\\.]?[pP]?\\d*\\d";
final String RS_REGEX = "Rs[.]?\\s*[\\d,]*[.]?\\d*\\d";

// Separate them with '|' operator and wrap them in two distinct matching groups
final String MONEY_OR_RS = String.format("(%s)|(%s)", MONEY_REGEX, RS_REGEX);

// Prepare some sample inputs
String[] inputs = new String[] { "$100", "Rs.150", "foo" };

Pattern p = Pattern.compile(MONEY_OR_RS);

// Test each inputs
Matcher m = null;
for (String input : inputs) {
if (m == null) {
m = p.matcher(input);
} else {
m.reset(input);
}

if (m.matches()) {
System.out.println(String.format("m.group(0) => %s\nm.group(1) => %s\n", m.group(1), m.group(2)));
} else {
System.out.println(input + " doesn't match regexp.");
}
}
}

输出

    m.group(0) => $100    m.group(1) => null    m.group(0) => null    m.group(1) => Rs.150    foo doesn't match regexp.

关于java - 删除多个正则表达式的交集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17145516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com