How to split string into string and integer in java

I have String a="abcd1234" and I want to split it into String b="abcd" and Int c=1234 This separator code should apply to all inputs like ab123456 and acff432, etc. How to break this type of string. Is it possible?

+6
source share
6 answers

You can try breaking up the regular expression, for example (?<=\D)(?=\d) . Try the following:

 String str = "abcd1234"; String[] part = str.split("(?<=\\D)(?=\\d)"); System.out.println(part[0]); System.out.println(part[1]); 

displays

 abcd 1234 

You can Integer.parseInt(part[1]) String digit on Integer using Integer.parseInt(part[1]) .

+10
source

You can do the following:

  • Separate by regular expression, for example split("(?=\\d)(?<!\\d)")
  • You have an array of strings with this, and you only need to parse it.
+2
source

Use regex:

 Pattern p = Pattern.compile("([az]+)([0-9]+)"); Matcher m = p.matcher(string); if (!m.find()) { // handle bad string } String s = m.group(1); int i = Integer.parseInt(m.group(2)); 

I did not compile this, but you should get this idea.

+1
source

Brute force decision.

 String a = "abcd1234"; int i; for(i = 0; i < a.length(); i++){ char c = a.charAt(i); if( '0' <= c && c <= '9' ) break; } String alphaPart = a.substring(0, i); String numberPart = a.substring(i); 
0
source

Use the regular expression "[^ A-Z0-9] + | (? <= [AZ]) (? = [0-9]) | (? <= [0-9]) (? = [AZ])" to break a piece alphabetically and numbers.

eg.

 String str = "ABC123DEF456"; 

Then the output using this regular expression will be:

ABC 123 DEF 456

For complete code, please visit the following URL:

http://www.zerotoherojava.com/split-string-by-characters-and-numbers/

0
source
 public static void main(String... s) throws Exception { Pattern VALID_PATTERN = Pattern.compile("([A-Za-z])+|[0-9]*"); List<String> chunks = new ArrayList<String>(); Matcher matcher = VALID_PATTERN.matcher("ab1458"); while (matcher.find()) { chunks.add( matcher.group() ); } } 
-2
source

Source: https://habr.com/ru/post/945993/