问题

我是正规表达的新手,非常感谢你的帮助。我正在尝试将一个表达式组合在一起,该表达式将使用未被单引号或双引号括起的所有空格分割示例字符串。我的最后一次尝试看起来像这样:(?!")并且工作不太好。在报价之前,它正在拆分空间。

示例输入:

This is a string that "will be" highlighted when your 'regular expression' matches something.

期望的输出:

This
is
a
string
that
will be
highlighted
when
your
regular expression
matches
something.

注意,"will be"'regular expression'之间保留了单词之间的空格。


#1 热门回答(210 赞)

我不明白为什么所有其他人都在提出如此复杂的正则表达式或如此长的代码。从本质上讲,你希望从字符串中获取两种内容:不是空格或引号的字符序列,以及以引号开头和结尾的字符序列,两种引号之间没有引号。你可以使用此正则表达式轻松匹配这些内容:

[^\s"']+|"([^"]*)"|'([^']*)'

我添加了捕获组,因为你不希望列表中的引号。

此Java代码构建列表,添加捕获组(如果匹配以排除引号),并在捕获组不匹配时添加整体正则表达式匹配(未匹配的单词匹配)。

List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    if (regexMatcher.group(1) != null) {
        // Add double-quoted string without the quotes
        matchList.add(regexMatcher.group(1));
    } else if (regexMatcher.group(2) != null) {
        // Add single-quoted string without the quotes
        matchList.add(regexMatcher.group(2));
    } else {
        // Add unquoted word
        matchList.add(regexMatcher.group());
    }
}

如果你不介意在返回的列表中使用引号,则可以使用更简单的代码:

List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    matchList.add(regexMatcher.group());
}

#2 热门回答(12 赞)

StackOverflow上有几个问题在使用正则表达式的各种上下文中涵盖了同一个问题。例如:

  • 解析字符串:提取单词和短语
  • 解析空格分隔文本的最佳方法

UPDATE:用于处理单引号和双引号字符串的示例正则表达式。编号:How can I split on a string except when inside quotes?

m/('.*?'|".*?"|\S+)/g

使用快速Perl片段对此进行测试,输出如下所示。如果它们在引号之间(不确定是否需要),也适用于空字符串或仅空白字符串。

This
is
a
string
that
"will be"
highlighted
when
your
'regular expression'
matches
something.

请注意,这确实包括匹配值中的引号字符本身,但你可以使用字符串替换删除它,或修改正则表达式以不包括它们。我现在将其留作读者或其他海报的练习,因为凌晨2点已经太晚了,不能再乱用正则表达式了;)


#3 热门回答(5 赞)

如果要在字符串中允许转义引号,可以使用以下内容:

(?:(['"])(.*?)(?<!\\)(?>\\\\)*\1|([^\s]+))

引用的字符串将是第2组,单个未引用的字符将是第3组。

你可以在这里尝试各种字符串:http://www.fileformat.info/tool/regex.htmorhttp://gskinner.com/RegExr/


原文链接