代码之家  ›  专栏  ›  技术社区  ›  northpole

如何使用正则表达式匹配括号内的文本?

  •  10
  • northpole  · 技术社区  · 15 年前

    我有以下模式:

    (COMPANY) -277.9887 (ASP,) -277.9887 (INC.) 
    

    ASP公司。

    目前,我有以下代码,它一直返回原始模式(我假设,因为组都位于第一个“(”和最后一个“)”之间)

    Pattern p = Pattern.compile("((.*))",Pattern.DOTALL);
    Matcher matcher = p.matcher(eName);
    while(matcher.find())
    {
        System.out.println("found match:"+matcher.group(1));
    }
    

    我正在努力得到我需要的结果,并感谢任何帮助。我不担心在得到每个组后连接结果,只需要得到每个组。

    5 回复  |  直到 15 年前
        1
  •  29
  •   chaos    15 年前
    Pattern p = Pattern.compile("\\((.*?)\\)",Pattern.DOTALL);
    
        2
  •  6
  •   ptomli    15 年前

    你的.*量词是“贪婪的”,所以是的,它抓住了第一个和最后一个可用括号之间的所有内容。正如chaos简洁地说:),使用。*?是一个非贪婪的量词,因此它将在保持匹配的同时尽可能少地获取。

    您需要在正则表达式中转义括号,否则它将成为另一个组。假设字符串中有文字括号。我怀疑你在最初的问题中提到的模式实际上是你的字符串。

    必修的

    如果必须为它们设置值,那么您希望使用+而不是*,+为1或更多,*为零或更多,因此*将匹配文本字符串“()”

    例如:“(.+?)”

        3
  •  1
  •   Chetan Laddha    7 年前

    * Description about casting regular expression: \(+\s*([^\s)]+)\s*\)+
    
    * \(+ : Exactly matches character "(" at least once
    * \s* : matches zero to any number white character.
    * ( : Start of Capturing group
    * [^\s)]+: match any number of character except ^, ) and spaces.
    * ) : Closing of capturing group.
    * \s*: matches any white character(0 to any number of character)
    * \)*: Exactly matches character ")" at least once.
    
    
    private static Pattern REGULAR_EXPRESSION = Pattern.compile("\\(+\\s*([^\\s)]+)\\s*\\)+");
    
        4
  •  0
  •   Oliver    15 年前

    不是对你问题的直接回答,但我建议你使用 RegxTester 快速找到答案和未来的任何问题。它允许您进行实时测试。

        5
  •  0
  •   Brent Writes Code    15 年前

    如果您的字符串总是这样,您可以只使用几个调用来替换所有字符串。这似乎对我有用:

    String eName = "(COMPANY) -277.9887 (ASP,) -277.9887 (INC.)";
            String eNameEdited = eName.replaceAll("\\).*?\\("," ").replaceAll("\\(|\\)","");
            System.out.println(eNameEdited);