如何在字符串数组中包含特殊字符.同时使用正则表达式模式的特殊字符拆分字符串


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 数组,但我当前的代码不包括特殊字符,它跳过了特殊字符 请帮帮我,提前谢谢....

要在 Java 中拆分和保留分隔符,您需要使用 lookarounds:将前瞻和后视与您选择的分隔符相结合。

在您的情况下,分隔符ASCII 字母或数字以外的任何字符。它可以通过以下方式实现

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

请注意,您不需要[A-Z]因为使用的是CASE_INSENSITIVE标志。

请参阅 IDEONE 演示,这里是正则表达式演示。

正则表达式匹配两个空位置,它们是

  • (?<=[^a-z0-9]) - 前面有 a-zA-Z0-9 以外的字符
  • (?=[^a-z0-9]) - 后跟除 a-zA-Z0-9 以外的字符。

最新更新