我有一个这样的 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 创建的? IE。他们匹配messageFormat?
非常感谢!
最佳答案
您可以使用 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
如果要捕获 token ,请使用大括号,如下所示:
Pattern pat = Pattern.compile("^This is token one (\\w+), and token two (\\w+)$");
您可以使用
mat.group(1)
和 mat.group(2)
检索组。关于java - 检查字符串是否与 Java 中的特定 MessageFormat 匹配?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17805603/