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
But what I get is:
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
I want to split the above string into String array of object including the special characters but my current code is not including the special character,its skipping the special character Please help me out,Thanks in advance....
最佳答案
要在 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-z
以外的字符开头,A-Z
或0-9
-
(?=[^a-z0-9])
- 后跟除a-z
以外的字符,A-Z
或0-9
.
关于java - 如何将特殊字符包含到字符串数组中。同时使用正则表达式模式的特殊字符拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34015637/