如何在字符串数组中包含特殊字符。同时使用Regex Pattern的特殊字符拆分字符串

时间:2015-12-01 08:18:45

标签: java regex

String s = "select from(select * LEAF_CATEG_ID,a.FROM_EMAIL_ADDRESS,a.HARD_BOUNCE_TYPE";
    Pattern p=Pattern.compile("[^a-zA-Z0-9]",Pattern.CASE_INSENSITIVE);
    String[] parts=p.split(s);

    for(int i=0;i<parts.length;i++){
        System.out.println("After finding special characters i am able to split the characters:"+parts[i]);

    }

我的期望输出是:

After finding special characters i am able to split the characters:select
After finding special characters i am able to split the characters:from
After finding special characters i am able to split the characters:(
After finding special characters i am able to split the characters:select
After finding special characters i am able to split the characters:*
After finding special characters i am able to split the characters:
After finding special characters i am able to split the characters:LEAF
After finding special characters i am able to split the characters:_
After finding special characters i am able to split the characters:CATEG
After finding special characters i am able to split the characters:_
After finding special characters i am able to split the characters:ID
After finding special characters i am able to split the characters:,
After finding special characters i am able to split the characters:a
After finding special characters i am able to split the characters:.
After finding special characters i am able to split the characters:FROM
  

但我得到的是:

After finding special characters i am able to split the characters:select
After finding special characters i am able to split the characters:from
After finding special characters i am able to split the characters:select
After finding special characters i am able to split the characters:
After finding special characters i am able to split the characters:
After finding special characters i am able to split the characters:LEAF
After finding special characters i am able to split the characters:CATEG
After finding special characters i am able to split the characters:ID
After finding special characters i am able to split the characters:a
After finding special characters i am able to split the characters:FROM
  

我想将上面的字符串拆分为包含特殊字符的对象的String数组但是我当前的代码不包含特殊字符,它跳过特殊字符   请帮助我,提前致谢....

1 个答案:

答案 0 :(得分:1)

要在Java中拆分和保留分隔符,您需要使用 lookarounds :前瞻和后视的组合,以及您选择的分隔符。

您的案例中的分隔符除ASCII字母或数字以外的任何字符。它可以通过

来实现
Pattern p=Pattern.compile("(?<=[^a-z0-9])|(?=[^a-z0-9])",Pattern.CASE_INSENSITIVE);

请注意,在使用[A-Z]标记时,您不需要CASE_INSENSITIVE

请参阅IDEONE demo,此处为the regex demo

正则表达式匹配两个

的空位置
  • (?<=[^a-z0-9]) - 前面加上a-zA-Z0-9
  • 以外的字符
  • (?=[^a-z0-9]) - 后跟a-zA-Z0-9以外的字符。
相关问题