如何忽略特定字符集之间的所有字符?

时间:2013-04-14 15:08:21

标签: java regex

我已经制定了以下要转换为代码的RegExp。但是遇到了一些麻烦:

“匹配至少一个=,忽略一切特殊字符集,无论这些特殊字符出现的频率如何。”

特殊集可以是:()|&!

示例,对于以下内容,我想忽略inout之间的所有内容:

(in == 1'b1) | !out & (sig==1'b0)

以下正则表达式将为群组制作一个:==) | !

\s*[=][&()!|=\s]*

但是我怎样才能匹配in和out之间的1'b1,这将是某种“匹配一个=到一个或多个特殊字符之后的任何内容?

1 个答案:

答案 0 :(得分:2)

如果它不一定是一个正则表达式那么你可以尝试这种方式

String data = "(in1 == 1'b1) |(in == 1'b1) | !out & (sig==1'b0) | !1out2 & (sig==1'b0)";
// I will try to split on every special character and space
String[] allTokens = data.split("[=()&|!\\s]+");
// but this will produce
// [, in1, 1'b1, in, 1'b1, out, sig, 1'b0, 1out2, sig, 1'b0]

// so I will try to filter tokens that are not only digits and letters
// with at least one letter
List<String> correctTokens = new ArrayList<>();

Pattern p = Pattern.compile("(?=.*[a-zA-Z])[a-zA-Z0-9]");
//(?=.*[a-zA-Z]) will return true if data will contain at least one letter
//and will contain only letters a-zA-Z and digits 0-9
for (String s : allTokens) {
    Matcher m = p.matcher(s);
    if (m.matches()) {
        correctTokens.add(s);
    }
}
System.out.println(correctTokens);

输出:

[in1, in, out, sig, 1out2, sig]
相关问题