【问题标题】:Java Regular expression does not match using Apache REJava 正则表达式不匹配使用 Apache RE
【发布时间】:2015-04-23 21:15:32
【问题描述】:

我有这个正则表达式字符串:

^[a-zA-Z0-9\t\s\n\r!$()*,-./:;=?@`][{}_~|]+$

对于以下情况,该 RE 应该返回 true:

!$()*,-./:;=?@`][{}_~|

我正在使用 Apache 的 RE 并在运行 match 函数时出现错误。
我认为我的正则表达式缺少某些内容,可能是使用特殊字符进行处理。
问题是,我的表达有什么问题?
这是我的RE匹配函数:

public static String runRegularExpression(String string, String regularExpression, int parenthesis)
{
    String result = null;

    try
    {
        RE reCmd = new RE(regularExpression);

        if (reCmd.match(string))
        {
            result = reCmd.getParen(parenthesis);
        }
    }
    catch (Exception re)
    {
    }

    return result;
}

【问题讨论】:

  • 再次转义所有反斜杠。
  • 我需要转义 RE 字符串吗?

标签: java regex apache


【解决方案1】:
  1. 您的正则表达式不能在字符类中间包含未转义的连字符。
  2. 如果您已经有\s,则无需匹配\n\t,因为\s 匹配所有空格,包括空格、制表符和换行符。
  3. [a-zA-Z0-9_] 可以缩短为 \w
  4. 反斜杠需要双转义。

试试这个正则表达式:

^[\\w\\s\\r!$()*,./:;=?@`{}\\[\\]~|-]+$

【讨论】:

  • 匹配输入:!$()*,-./:;=?@`][{}_~|
  • 不匹配输入:i ╣glε╧m♂▬!,♠•
  • 是的,我知道。这就是为什么它如此令人沮丧.. :)
  • 我想我找到了问题所在。我删除了输入中的字符 \ 并且它起作用了。也许我需要以某种方式逃避它......
  • 对不起不是这个\而是这个/
猜你喜欢
  • 2015-06-03
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多