Java正则表达式-拆分但忽略引号内的文本? [英] java Regex - split but ignore text inside quotes?

查看:68
本文介绍了Java正则表达式-拆分但忽略引号内的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅使用正则表达式方法,即String.replaceAll和ArrayList方法如何将字符串拆分为标记,但忽略引号内存在的定界符?分隔符是不是字母数字或带引号的文本的任何字符

using only regular expression methods, the method String.replaceAll and ArrayList how can i split a String into tokens, but ignore delimiters that exist inside quotes? the delimiter is any character that is not alphanumeric or quoted text

例如:字符串:

你好^世界'这*有两个令牌'

hello^world'this*has two tokens'

应输出:

  • 你好
  • worldthis *有两个令牌

推荐答案

使用

Use a Matcher to identify the parts you want to keep, rather than the parts you want to split on:

String s = "hello^world'this*has two tokens'";
Pattern pattern = Pattern.compile("([a-zA-Z0-9]+|'[^']*')+");
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
    System.out.println(matcher.group(0));
}

查看其在线运行情况: ideone

See it working online: ideone

这篇关于Java正则表达式-拆分但忽略引号内的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆