java - 匹配两个字符串,一个与 x,另一个与任意字符

标签 java regex string pattern-matching

我是正则表达式新手,所以没有得到这个。 我需要在 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 并确保 str1str2 中的每个字符在每个位置都相等,除非 处的相应位置str1'x'

关于java - 匹配两个字符串,一个与 x,另一个与任意字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26235585/

相关文章:

java - Glide 不在第一个 fragment "automatically"中显示图像

java - 无法从 DrawerLayout 项目检查当前 Activity

java - 如何从 XML 解析中正确显示内容?

Java正则表达式问题

Python Regex 在字符串上停止

javascript - 使用 jQuery 将长字符串拆分为文本 block

c++ - 如何将字符串转换成char *数组

c - char* 操作期间的内存泄漏

java - 使用鼠标在网格 Pane 中添加节点

string - 为什么 NSError 的 localizedDescription 说可选 ("description")?