我是正则表达式新手,所以没有得到这个。
我需要在 Java 中匹配两个 String
,其中一个字符串包含 x 的数量,其他字符串可以在这些位置包含任何字符。
For example -
String 1 - this is the time xxxx when i get up
String 2 - this is the time 0830 when i get up
这两个字符串应该匹配并返回 true。
请提出建议。
谢谢。
正如你们很多人提到的,这个问题不是很清楚。我将添加更多详细信息 -
1. x can appear 2 to any number of times.
2. Strings will be dynamic, or in other words, they'll be passed to a method -
public boolean doesMatch(String str1, String str2) {
// matching code
return false;
}
所以另一个例子可能是 -
this is xxxday and i xxxx it
this is friday and i like it
这两个字符串也应该匹配。
最佳答案
您需要重建状态引擎:
public boolean doesMatch(String str1, String str2) {
if (str1.length() != str2.length())
return false;
for (int i = 0; i < str1.length(); i++)
if (str1.charAt(i) != 'x' && str1.charAt(i) != str2.charAt(i))
return false;
return true;
}
此循环遍历 str1
并确保 str1
和 str2
中的每个字符在每个位置都相等,除非 处的相应位置str1
是'x'
。
关于java - 匹配两个字符串,一个与 x,另一个与任意字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26235585/