我尝试生成我的Pattern
,以便能够在UI中通过JTextfield
设置/添加/编辑它
对于variant2,它可以正常工作,但如果我尝试添加多个模式(variant1),它就会停止工作。
你能告诉我我做错了什么吗?
以下是代码的相关部分:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestSomeStaff {
String getPattern(String s) {
String p = "";
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i))) {
p += "\\" + "w";
} else if (Character.isDigit(s.charAt(i))) {
p += "\\" + "d";
} else {
p += s.charAt(i);
}
}
return p;
}
public static void main(String[] args) {
String code1 = "11XXX08_XX000XX__XX11";
String code2 = "11XXX08_XX000X__XX11";
TestSomeStaff t = new TestSomeStaff();
// String p="("+t.getPattern(code1) + ") | ("+t.getPattern(code2)+")";
// //variant1
String p = t.getPattern(code1); // variant 2
System.out.println(t.getPattern(code1));
Pattern pat = Pattern.compile(p);
Matcher m = pat.matcher(code1);
System.out.println("pattern:" + m.pattern());
if (m.find()) {
System.out.println(m.group());
}
}
}
var1输出:
\d\d\w\w\w\d\d_\w\w\d\d\d\w\w__\w\w\d\d
pattern:(\d\d\w\w\w\d\d_\w\w\d\d\d\w\w__\w\w\d\d) | (\d\d\w\w\w\d\d_\w\w\d\d\d\w__\w\w\d\d)
var2输出:
\d\d\w\w\w\d\d_\w\w\d\d\d\w\w__\w\w\d\d
pattern:\d\d\w\w\w\d\d_\w\w\d\d\d\w\w__\w\w\d\d
11XXX08_XX000XX__XX11
答案 0 :(得分:1)
variant1
模式中的空格很重要。如果删除空格,则变体将起作用。