java - 检查 String 是否与 Java 中的特定 MessageFormat 匹配?

标签 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 创建的? IE。它们匹配消息格式吗?

非常感谢!

最佳答案

您可以使用 Regular Expressions 来做到这一点和 PatternMatcher类。 一个简单的例子:

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/

相关文章:

java - 如何在 android studio 中以编程方式触发图像按钮

java - 如何为javafx面板添加边框?

ruby - 是否有与 Java MessageFormat 等效的 Ruby?

java - Java 中 MessageFormat 的好处

java - JDK 1.5 中的 MessageFormat.format 和 String.format 有什么区别?

Java MessageFormat - 问题转义字符

java - 如何在选择文本时停止 EditText 显示键盘?

java - 使用 Hibernate 从 Postgres 枚举到 Java

java - php javascript java applet 智能卡在服务器上签名pdf