【问题标题】:Use regex to split with char avoid between two char使用正则表达式与字符分割避免两个字符之间
【发布时间】:2017-02-03 11:22:20
【问题描述】:

考虑我有一个这样的字符串:

String str = "a,b,c,d," + char1 + "e,f" + char2 + ",g,h,i,j";

如何使用, 拆分所有内容,避免char1char2 之间的所有内容,而不是,

只有当char1 = '('char2 = ')' 像这样时,我才能使用此正则表达式,(?![^()]*\\)) 进行拆分:

char char1 = '(', char2 = ')';
String str = "a,b,c,d," + char1 + "e,f,g" + char2 + ",h";
String s2[] = str.toString().split(",(?![^()]*\\))");

我得到这个结果:

a
b
c
d
e,f,g
h

那么如何将其概括为使用char1char2 中的任何字符。

谢谢。

【问题讨论】:

  • “任何字符”是什么意思? char1 和/或 char2 可以是 ','(逗号)吗?
  • 这个问题似曾相识……看看here
  • @Betlista nope 抱歉不能是, 我忘了这部分我会编辑我的问题
  • 是否可以在连接之前拆分字符串?如果没有,您是否能够在连接之前控制 char1 和 char2 是什么?这样你就可以在两者中输入一个通配符,这样你就可以将正则表达式集中在那个通配符上。
  • 使用"(?:" +Pattern.quote(char1) + ".*?" + Pattern.quote(char2) + "|[^,])+" 匹配令牌。

标签: java regex string split


【解决方案1】:

使用匹配方法:匹配您定义的字符之间的任何子字符串,然后匹配任何不等于, 的字符和用户定义的字符。

char char1 = '|', char2 = ')';
String str = "a,b,c,d," + char1 + "e,f,g" + char2 + ",h";
String ch1_quoted = Pattern.quote(Character.toString(char1));
String ch2_quoted = Pattern.quote(Character.toString(char2));
List<String> s2 = new ArrayList<>();
Pattern pattern = Pattern.compile(ch1_quoted + "(.*?)" 
                                    + ch2_quoted + "|[^," + ch1_quoted + ch2_quoted + "]+", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()){
    if (matcher.group(1) != null) {
        s2.add(matcher.group(1));
        System.out.println(matcher.group(1));
    } else {
        s2.add(matcher.group(0)); 
        System.out.println(matcher.group(0));
    }
} 

请参阅Java demo

Pattern.DOTALL 用于使 . 匹配换行符 - 以防万一。

请参阅sample code regex demo

【讨论】:

  • 对不起,你能改进你的模式以删除结果中的两个字符,而不是|e,f,g),结果应该没有这两个字符,就像e,f,g
  • 我认为这是我的错误,我把a b c d (e,f,g) h 改为b c d e,f,g h
  • ideone.com/yWoUsa。不确定它是否会按预期工作,因为我不知道您的数据是什么样的。
  • ooohh 这是它完美的工作你很好谢谢你可以编辑你的答案我已经改变了我的问题
猜你喜欢
  • 2021-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
相关资源
最近更新 更多