Good day. There is a line:

String str = "887i9qWerty1qwerty24"; 

I try to highlight the words first:

 Pattern p = Pattern.compile("[a-zA-Z]+"); Matcher m = p.matcher(str); while (m.find()) { System.out.println(m.group()); } 

Then the numbers:

 Pattern p = Pattern.compile("[0-9]+"); Matcher m = p.matcher(str); while (m.find()) { System.out.println(m.group()); } 

Is it possible to isolate both words and numbers in one expression?

  • not. that is, you can pull out words and text, but you cannot separate them into 2 parts in one regular season - you can't - Senior Pomidor
  • I can do this not using regular expressions, but get the result in two ArrayList. (or as you need) - Denis Kotlyarov
  • Denis, thank you. But I can do it myself :) I thought how cleverly a pattern could be drawn, where numbers and words at their border are separated. - Vard32
  • Ok, let's say there is some sort of regular program that does what you want, the question is, how will you get alternate numbers from it then words and how will you distinguish them from each other? - Artem Konovalov
  • @ArtemKonovalov and what, is it difficult to distinguish letters and numbers?)) Regex101.com/r/fK0tW1/1 - Alexey Shimansky

1 answer 1

If you just need to get the words and numbers in one thread, without distinguishing them, then you can use the expression [a-zA-Z]+|[0-9]+ :

 String str = "887i9qWerty1qwerty24"; Pattern p = Pattern.compile("[a-zA-Z]+|[0-9]+"); Matcher m = p.matcher(str); while (m.find()) { System.out.println(m.group()); } 

If you need to distinguish them, you can select them into different groups, something like this:

 String str = "887i9qWerty1qwerty24"; Pattern p = Pattern.compile("([a-zA-Z]+)|([0-9]+)"); Matcher m = p.matcher(str); while (m.find()) { String word = m.group(1); String number = m.group(2); if (word != null) { System.out.println("Word: " + word); } else { System.out.println("Number: " + number); } } 
  • Roman, great. The first option, what you need! Thank you - Vard32