Need help to split line in java using regex

I have a string like "portal100common2055" .

I would like to break it into two parts, where the second part should contain only numbers.

"portal200511sbet104" will become "portal200511sbet" , "104"

Could you help me with this?

+4
source share
2 answers

Like this:

  Matcher m = Pattern.compile("^(.*?)(\\d+)$").matcher(args[0]); if( m.find() ) { String prefix = m.group(1); String digits = m.group(2); System.out.println("Prefix is \""+prefix+"\""); System.out.println("Trailing digits are \""+digits+"\""); } else { System.out.println("Does not match"); } 
+5
source
 String[] parts = input.split("(?<=\\D)(?=\\d+$)"); if (parts.length < 2) throw new IllegalArgumentException("Input does not end with numbers: " + input); String head = parts[0]; String numericTail = parts[1]; 

This more elegant solution uses the look and look of regular expression features.

Explanation:

  • (?<=\\D) means at the current point, make sure that the previous characters do not end with a digit (no digit is expressed as \D )
  • (?=\\d+$) means t current point, make sure that only digits are found at the end of the input (the digit is expressed as \D )

It will only be truth at the right point, which you want to divide by input

+3
source

All Articles