正则表达式,用于在未被单引号或双引号括起时使用空格分割字符串

car*_*lsz 107 java regex split

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

输入示例:

This is a string that "will be" highlighted when your 'regular expression' matches something.
Run Code Online (Sandbox Code Playgroud)

期望的输出:

This
is
a
string
that
will be
highlighted
when
your
regular expression
matches
something.
Run Code Online (Sandbox Code Playgroud)

请注意"will be"'regular expression'保留单词之间的空格.

Jan*_*rts 232

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

[^\s"']+|"([^"]*)"|'([^']*)'
Run Code Online (Sandbox Code Playgroud)

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

此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());
    }
} 
Run Code Online (Sandbox Code Playgroud)

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

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

  • 这个答案的问题是无与伦比的引用:"约翰的母亲"结果分裂为"[约瑟夫,母亲]" (3认同)
  • 要解决 leonbloy 大纲的问题,您可以稍微重新排序操作数并省略空格组中的引号:``"([^"]*)"|'([^']*)'|[^ \s]+``。 (2认同)
  • 基于此和其他答案,以下正则表达式允许在引号内转义字符: `"([^"\\]*(?:\\.[^"\\]*)*)"|'([^' \\]*(?:\\.[^'\\]*)*)'|[^\s]+`。请参阅/sf/ask/398666831/ (2认同)

Jay*_*Jay 13

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

更新:示例正则表达式处理单引号和双引号字符串.参考:我怎样才能拆分字符串,除非在引号内?

m/('.*?'|".*?"|\S+)/g 
Run Code Online (Sandbox Code Playgroud)

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

This
is
a
string
that
"will be"
highlighted
when
your
'regular expression'
matches
something.
Run Code Online (Sandbox Code Playgroud)

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


mcr*_*ley 5

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

(?:(['"])(.*?)(?<!\\)(?>\\\\)*\1|([^\s]+))
Run Code Online (Sandbox Code Playgroud)

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

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