我有像这样的MessageFormat;
final MessageFormat messageFormat = new MessageFormat("This is token one {0}, and token two {1}");
我只是想知道我是否有类似的字符串;
String shouldMatch = "This is token one bla, and token two bla";
String wontMatch = "This wont match the above MessageFormat";
如何检查上述字符串是否是使用messageFormat创建的?即他们匹配messageFormat?
非常感谢!
答案 0 :(得分:6)
您可以使用Regular Expressions和Pattern以及Matcher类来完成此操作。 一个简单的例子:
Pattern pat = Pattern.compile("^This is token one \\w+, and token two \\w+$");
Matcher mat = pat.matcher(shouldMatch);
if(mat.matches()) {
...
}
正则表达式的解释:
^ = beginning of line
\w = a word character. I put \\w because it is inside a Java String so \\ is actually a \
+ = the previous character can occur one ore more times, so at least one character should be there
$ = end of line
如果要捕获令牌,请使用以下大括号:
Pattern pat = Pattern.compile("^This is token one (\\w+), and token two (\\w+)$");
您可以使用mat.group(1)
和mat.group(2)
检索群组。
答案 1 :(得分:0)
除了Reg Ex的答案之外,还可以使用我刚刚开发的代码来完成:
public class Points {
private int start;
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
private int end;
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
}
public class Split {
public static void main(String[] args) {
final MessageFormat messageFormat = new MessageFormat("This is token one {0}, and token two {1}");
ArrayList<String> list = new ArrayList<String>();
list.add("This is token one bla, and token two bla");
list.add("This wont match the above MessageFormat");
list.add("This wont match the above MessageFormat");
list.add("This wont match the above MessageFormat");
list.add("This is token one bla, and token two bla");
list.add("This wont match the above MessageFormat");
Format[] format = messageFormat.getFormats();
int del = format.length;
ArrayList<String> delimeters = new ArrayList<String>();
for (int i = 0; i < del; i++) {
delimeters.add("{" + i + "}");
}
//System.out.println(messageFormat.toPattern());
ArrayList<Points> points = new ArrayList<Points>();
int counter = 0;
for (String x : delimeters) {
Points tmp = new Points();
tmp.setStart(counter);
int ending = messageFormat.toPattern().indexOf(x);
counter = ending + x.length();
tmp.setEnd(ending);
points.add(tmp);
}
for (String x : list) {
boolean match = true;
for (Points y : points) {
if (match) {
if (x.substring(y.getStart(), y.getEnd()).equals(messageFormat.toPattern().substring(y.getStart(), y.getEnd()))) {
} else {
match = false;
}
}
}
if (match) {
System.out.println("Match!!!");
} else {
System.out.println("Not Match!!");
}
}
}
}
运行它会打印输出
匹配!!!
不匹配!!
不匹配!!
不匹配!!
匹配!!!
不匹配!!
希望你喜欢它!