Java 不区分大小写的 String split() 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16581977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Case insensitive String split() method
提问by Sanjaya Liyanage
When I perform
当我执行
String test="23x34 ";
String[] array=test.split("x"); //splitting using simple letter
I got two items in array as 23 and 34
我在数组中有两个项目 23 和 34
but when I did
但是当我这样做的时候
String test="23x34 ";
String[] array=test.split("X"); //splitting using capitalletter
I got one item in array 23x34
我在 23x34 数组中得到了一项
So is there any way I can use the split method as case insensitive or whether there is any other method that can help?
那么有什么方法可以将 split 方法用作不区分大小写的方法,或者是否有任何其他方法可以提供帮助?
采纳答案by harsh
Use regex pattern [xX]
in split
使用正则表达式模式[xX]
中split
String x = "24X45";
String[] res = x.split("[xX]");
System.out.println(Arrays.toString(res));
回答by zEro
Java's String class' split method also accepts regex.
Java 的 String 类的 split 方法也接受正则表达式。
To keep things short, this should help you: http://www.coderanch.com/t/480781/java/java/String-split
为了保持简短,这应该可以帮助您:http: //www.coderanch.com/t/480781/java/java/String-split
回答by njzk2
split
uses, as the documentation suggests, a regexp. a regexp for your example would be :
split
正如文档所建议的那样,使用正则表达式。您的示例的正则表达式将是:
"[xX]"
Also, the (?i)
flag toggles case insensitivty. Therefore, the following is also correct :
此外,该(?i)
标志切换不区分大小写。因此,以下内容也是正确的:
"(?i)x"
In this case, x
can be any litteral properly escaped.
在这种情况下,x
可以正确转义任何文字。
回答by jlordo
You can also use an embedded flag in your regex:
您还可以在正则表达式中使用嵌入式标志:
String[] array = test.split("(?i)x"); // splits case insensitive
回答by anana
You could use a regex as an argument to split
, like this:
您可以使用正则表达式作为 的参数split
,如下所示:
"32x23".split("[xX]");
Or you could use a StringTokenizer
that lets you set its set of delimiters, like this:
或者您可以使用 aStringTokenizer
来设置它的分隔符集,如下所示:
StringTokenizer st = new StringTokenizer("32x23","xX");
// ^^ ^^
// string delimiter
This has the advantage that if you want to build the list of delimiters programatically, for example for each lowercase letter in the delimiter list add its uppercase corespondent, you can do this and then pass the result to the StringTokenizer
.
这样做的好处是,如果您想以编程方式构建分隔符列表,例如为分隔符列表中的每个小写字母添加其大写对应字母,您可以这样做,然后将结果传递给StringTokenizer
.
回答by user2981810
I personally prefer using
我个人更喜欢使用
String modified = Pattern.compile("x", Pattern.CASE_INSENSITIVE).matcher(stringContents).replaceAll(splitterValue);
String[] parts = modified.split(splitterValue);
In this way you can ensure any regex will work, as long as you have a unique splitter value
通过这种方式,您可以确保任何正则表达式都可以工作,只要您有一个唯一的拆分器值