Case insensitive String split() method

前端 未结 6 1581
北海茫月
北海茫月 2020-12-10 01:48

When I perform

String test=\"23x34 \";
String[] array=test.split(\"x\"); //splitting using simple letter

I got two items in array as 23 and

相关标签:
6条回答
  • 2020-12-10 02:28

    split uses, as the documentation suggests, a regexp. a regexp for your example would be :

    "[xX]"
    

    Also, the (?i) flag toggles case insensitivty. Therefore, the following is also correct :

    "(?i)x"
    

    In this case, x can be any litteral properly escaped.

    0 讨论(0)
  • 2020-12-10 02:33

    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

    0 讨论(0)
  • 2020-12-10 02:37

    Java's String class' split method also accepts regex.

    To keep things short, this should help you: http://www.coderanch.com/t/480781/java/java/String-split

    0 讨论(0)
  • 2020-12-10 02:38

    You can also use an embedded flag in your regex:

    String[] array = test.split("(?i)x"); // splits case insensitive
    
    0 讨论(0)
  • 2020-12-10 02:41

    You could use a regex as an argument to split, like this:

    "32x23".split("[xX]");
    

    Or you could use a StringTokenizer that lets you set its set of delimiters, like this:

    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.

    0 讨论(0)
  • 2020-12-10 02:44

    Use regex pattern [xX] in split

    String x = "24X45";
    String[] res = x.split("[xX]");
    System.out.println(Arrays.toString(res));
    
    0 讨论(0)
提交回复
热议问题