How to split String without regex [duplicate]

耗尽温柔 提交于 2021-02-08 12:16:34

问题


In my Java application I need to find indices and split strings using the same "target" for both occasions. The target is simply a dot.

Finding indices (by indexOf and lastIndexOf) does not use regex, so

String target = ".";
String someString = "123.456";
int index = someString.indexOf(target); // index == 3

gives me the index I need.

However, I also want to use this "target" to split some strings. But now the target string is interpreted as a regex string. So I can't use the same target string as before when I want to split a string...

String target = ".";
String someString = "123.456";
String[] someStringSplit = someString.split(target); // someStringSplit is an empty array

So I need either of the following:

  1. A way to split into an array by a non-regex target
  2. A way to "convert" a non-regex target string into a regex string

Can someone help? Would you agree that it seems a bit odd of the standard java platform to use regex for "split" while not using regex for "indexOf"?


回答1:


You need to escape your "target" in order to use it as a regex. Try

String[] someStringSplit = someString.split(Pattern.quote(target));

and let me know if that helps.




回答2:


You can try this one.

String target = ".";
String someString = "123.456";
StringTokenizer tokenValue = new StringTokenizer(someString, target);

while (tokenValue.hasMoreTokens()) {
    System.out.println(tokenValue.nextToken());
}



回答3:


String::split do split without regex if the regex is:

  • a one-char String and this character is not one of the RegEx's meta characters .$|()[{^?*+\\
  • two-char String and the first char is the backslash and the second is not the ascii digit or ascii letter.

Please see String::split() source code for details.

For escaped '.' target it is going to be split without regex.



来源:https://stackoverflow.com/questions/39038102/how-to-split-string-without-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!