检查String是否与Java中的特定MessageFormat匹配?
作者:互联网
我有像这样的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?
非常感谢!
解决方法:
您可以使用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)检索组.
标签:java,messageformat 来源: https://codeday.me/bug/20190825/1720550.html