【问题标题】:RegEx To Ignore Text Between Quotes正则表达式忽略引号之间的文本
【发布时间】:2011-06-22 12:31:01
【问题描述】:

我有一个正则表达式,即[\\.|\\;|\\?|\\!][\\s]
这用于拆分字符串。但我不希望它在引号中拆分 . ; ? !

【问题讨论】:

  • 我认为您需要开始考虑解析,而不是正则表达式拆分。不过,使用一些示例输入会更容易回答。
  • 解析是一种选择,但我想知道如何在 RegEx 中进行解析。他们有办法做到这一点吗?
  • RegEx 不是用于此目的的工具,无论您想用它做什么,因为它不能替代解析。我认为你需要放弃这个任务并学习上面提到的解析。
  • 我认为正则表达式在这种情况下可能遇到的问题称为“灾难性回溯”。
  • 我已经为单词和音节部分做了解析器,但我想做一些与句子部分不同的事情。我想我将不得不回到过去。

标签: java regex pattern-matching


【解决方案1】:

这是我为了忽略匹配中的引号而做的。

(?:[^\"\']|(?:\".*?\")|(?:\'.*?\'))*?    # <-- append the query you wanted to search for - don't use something greedy like .* in the rest of your regex.

为了适应你的正则表达式,你可以这样做

(?:[^\"\']|(?:\".*?\")|(?:\'.*?\'))*?[.;?!]\s*

【讨论】:

    【解决方案2】:

    我不会使用拆分,而是使用 Pattern & Matcher。

    演示:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Main {
    
        public static void main(String[] args) {
    
            String text = "start. \"in quotes!\"; foo? \"more \\\" words\"; bar";
    
            String simpleToken = "[^.;?!\\s\"]+";
    
            String quotedToken =
                    "(?x)             # enable inline comments and ignore white spaces in the regex         \n" +
                    "\"               # match a double quote                                                \n" +
                    "(                # open group 1                                                        \n" +
                    "  \\\\.          #   match a backslash followed by any char (other than line breaks)   \n" +
                    "  |              #   OR                                                                \n" +
                    "  [^\\\\\r\n\"]  #   any character other than a backslash, line breaks or double quote \n" +
                    ")                # close group 1                                                       \n" +
                    "*                # repeat group 1 zero or more times                                   \n" +
                    "\"               # match a double quote                                                \n";
    
            String regex = quotedToken + "|" + simpleToken;
    
            Matcher m = Pattern.compile(regex).matcher(text);
    
            while(m.find()) {
                System.out.println("> " + m.group());
            }
        }
    }
    

    产生:

    > start
    > "in quotes!"
    > foo
    > "more \" words"
    > bar
    

    如您所见,它还可以处理带引号的标记内的转义引号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      • 2017-01-23
      • 2011-08-07
      • 2022-07-29
      • 1970-01-01
      • 2020-10-23
      相关资源
      最近更新 更多