java替换单引号为空格_当不被单引号或双引号包围时使用空格拆分字符串的正则表达式...

我不明白为什么所有其他人都提出这么复杂的正则表达式或这么长的代码。本质上,你想从你的字符串中获取两种东西:不是空格或引号的字符序列,以及以引号开头和结尾的字符序列,两种引号之间没有引号。您可以很容易地将这些内容与这个正则表达式相匹配:[^\s"']+|"([^"]*)"|'([^']*)'

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

此Java代码构建列表,如果匹配以排除引号,则添加捕获组;如果捕获组不匹配,则添加总体regex匹配(未引用的单词匹配)。List matchList = new ArrayList();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 matchList = new ArrayList();Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");

Matcher regexMatcher = regex.matcher(subjectString);while (regexMatcher.find()) {

matchList.add(regexMatcher.group());}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值