【问题标题】:Java ignore special characters in string matchingJava忽略字符串匹配中的特殊字符
【发布时间】:2015-01-22 06:42:53
【问题描述】:

我想匹配 java 中的两个字符串,例如。

文字:János

搜索表达式:Janos

由于我不想替换所有特殊字符,我想我可以将á 设为通配符,这样所有内容都可以匹配此字符。例如,如果我用Jxnos 搜索János,它应该会找到它。当然,文本中可能有多个特殊字符。有谁知道我如何通过任何模式匹配器实现这一点,还是我必须逐个字符比较?

【问题讨论】:

  • 请阅读基于规范化字符串的可能方法,例如stackoverflow.com/questions/3322152/… - 这种方法可以很容易地删除特殊字符
  • 感谢您提供的信息,我没有考虑使用 apache.commons 库。 stripAccents 正是我所需要的。如果你愿意写你的评论作为回答,我可以接受。
  • 完成 - 很高兴这对你有用

标签: java string compare special-characters


【解决方案1】:

使用带有J\\Snos 的模式和匹配器类作为正则表达式。 \\S 匹配任何非空格字符。

String str = "foo János bar Jxnos";
Matcher m = Pattern.compile("J\\Snos").matcher(str);
while(m.find())
{
    System.out.println(m.group());
}

输出:

János
Jxnos

【讨论】:

  • 为什么不用. 而不是\\S
  • 因为我认为 op 不想在中间允许空格字符。
【解决方案2】:

一种可能的解决方案是借助 Apache Commons StringUtils.stripAccents(input) 方法去除重音:

String input = StringUtils.stripAccents("János");
System.out.println(input); //Janos

请务必阅读基于 Normalizer 类的更详细的方法:Is there a way to get rid of accents and convert a whole string to regular letters?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    相关资源
    最近更新 更多