我有一个像这样的 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。它们匹配消息格式吗?
非常感谢!
最佳答案
您可以使用 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 - 检查 String 是否与 Java 中的特定 MessageFormat 匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17805603/