It is necessary to split the string into two parts in java

I have a string that contains an adjacent piece of numbers, and then a continuous piece of characters. I need to break them into two parts (one integer part and one line).

I tried using String.split("\\D", 1) , but it eats the first character. I checked the entire String API and did not find a suitable method.

Is there any way to do this?

+6
java string regex regex-lookarounds lookaround
source share
2 answers

Use the return paths: str.split("(?<=\\d)(?=\\D)")

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

\d - character class for digits; \d is its negation. Thus, this zero-correspondence statement coincides with the position in which the preceding character is a digit (?<=\d) and the next character is not a digit (?=\D) .

References

Related Questions

  • The separation of Java is the use of my characters.
  • Is there a way to split strings with String.split () and enable separators?

Alternative solution using limited separation

The following also works:

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

It breaks just before we see a number. This is much closer to your original solution, except that since it does not actually correspond to an asymmetric symbol, it does not β€œeat it up”. In addition, it uses the limit of 2 , which you really need.

API Links

  • String.split(String regex, int limit)
    • If the limit n greater than zero, the pattern will be applied no more than n - 1 times, the length of the array will be no more than n , and the last record of the array will contain all the input data for the last Corresponding separator.
+13
source share

There is 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)}; } 

(I hope that it works only with a number or char - only strings) - cannot check it here, if not, consider it a general idea)

+3
source share

All Articles