我是正则表达式的新手,非常感谢您的帮助。我正在尝试将一个表达式组合在一起,该表达式将使用所有未用单引号或双引号引起来的空格来拆分示例字符串。我的最后一次尝试看起来像这样:效果(?!")
不佳。它在报价前的空格处分开。
输入示例:
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'
保留单词之间的空格。
我不明白为什么其他所有人都提出了如此复杂的正则表达式或如此长的代码。本质上,您想从字符串中获取两种东西:不是空格或引号的字符序列,以及两种引号之间以引号开头和结尾且中间没有引号的字符序列。您可以使用以下正则表达式轻松匹配这些内容:
[^\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());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句