Java Regex to split a string into int, double

I have a string that I want to split;

String x = "abc4.5efg2hij89k.9";

I want the result to be

abc, 4.5, efg, 2, hij, 89, k, .9

I can easily separate numbers and numbers. considered a character.

x.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)")
[abc, 4, ., 5, efg, 2, hij, 89, k., 9]

What is the best way to support doubles?

+4
source share
3 answers

Do you count letter characters instead of using a token \D?

String s = "abc4.5efg2hij89k.9";
String[] parts = s.split("(?<=[a-z])(?=[\\d.])|(?<=\\d)(?=[a-z])");
System.out.println(Arrays.toString(parts));

Output

[abc, 4.5, efg, 2, hij, 89, k, .9]
+5
source

You can match instead of splitting and then save the matches in a list of arrays.

[^\\d.]+|\\d*(?:\\.\\d+)?

Demo

String x = "abc4.5efg2hij89k.9";
Pattern regex = Pattern.compile("[^\\d.]+|\\d*(?:\\.\\d+)?");
Matcher matcher = regex.matcher(x);
ArrayList<String> returnValue= new ArrayList<String>();
while(matcher.find())
     {
         if(matcher.group().length() != 0)
         {
             returnValue.add(matcher.group());
         }
     }
System.out.println(returnValue);

Conclusion:

[abc, 4.5, efg, 2, hij, 89, k, .9]
+1
source
(?<=[a-zA-Z])(?=[^a-zA-Z])|(?<=[^a-zA-Z])(?=[a-zA-Z])

Share it. Check out the demo.

https://regex101.com/r/vN3sH3/19

0
source

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


All Articles