use*_*917 3 java messageformat
我有像这样的MessageFormat;
final MessageFormat messageFormat = new MessageFormat("This is token one {0}, and token two {1}");
Run Code Online (Sandbox Code Playgroud)
我只是想知道我是否有类似的字符串;
String shouldMatch = "This is token one bla, and token two bla";
String wontMatch = "This wont match the above MessageFormat";
Run Code Online (Sandbox Code Playgroud)
如何检查上述字符串是否是使用messageFormat创建的?即它们匹配messageFormat?
非常感谢!
您可以使用正则表达式和模式和匹配器类来完成此操作.一个简单的例子:
Pattern pat = Pattern.compile("^This is token one \\w+, and token two \\w+$");
Matcher mat = pat.matcher(shouldMatch);
if(mat.matches()) {
...
}
Run Code Online (Sandbox Code Playgroud)
正则表达式的解释:
^ = 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
Run Code Online (Sandbox Code Playgroud)
如果要捕获标记,请使用以下大括号:
Pattern pat = Pattern.compile("^This is token one (\\w+), and token two (\\w+)$");
Run Code Online (Sandbox Code Playgroud)
您可以使用mat.group(1)和检索组mat.group(2).