Need to split a string into two parts in java

做~自己de王妃 提交于 2019-11-27 19:30:20

问题


I have a string which contains a contiguous chunk of digits and then a contiguous chunk of characters. I need to split them into two parts (one integer part, and one string).

I tried using String.split("\\D", 1), but it is eating up first character. I checked all the String API and didn't find a suitable method.

Is there any method for doing this thing?


回答1:


Use lookarounds: str.split("(?<=\\d)(?=\\D)")

String[] parts = "123XYZ".split("(?<=\\d)(?=\\D)");
System.out.println(parts[0] + "-" + parts[1]);
// prints "123-XYZ"

\d is the character class for digits; \D is its negation. So this zero-matching assertion matches the position where the preceding character is a digit (?<=\d), and the following character is a non-digit (?=\D).

References

  • regular-expressions.info/Lookarounds and Character Class

Related questions

  • Java split is eating my characters.
  • Is there a way to split strings with String.split() and include the delimiters?

Alternate solution using limited split

The following also works:

    String[] parts = "123XYZ".split("(?=\\D)", 2);
    System.out.println(parts[0] + "-" + parts[1]);

This splits just before we see a non-digit. This is much closer to your original solution, except that since it doesn't actually match the non-digit character, it doesn't "eat it up". Also, it uses limit of 2, which is really what you want here.

API links

  • String.split(String regex, int limit)
    • If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.



回答2:


There's always an old-fashioned way:

private String[] split(String in) {    
  int indexOfFirstChar = 0;
  for (char c : in.toCharArray()) {
    if (Character.isDigit(c)) {
      indexOfFirstChar++;
    } else {
      break;
    } 
  }    
  return new String[]{in.substring(0,indexOfFirstChar), in.substring(indexOfFirstChar)};
}

(hope it works with digit-only or char-only Strings too - can't test it here - if not, take it as a general idea)



来源:https://stackoverflow.com/questions/2995606/need-to-split-a-string-into-two-parts-in-java

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