Combine multiple regexes in Java

I wrote a regular expression to omit characters after the first occurrence of some characters (and #)

String number = "(123) (456) (7890)#123";
number = number.replaceAll("[,#](.*)", ""); //This is the 1st regex

Then the second regular expression receives only numbers (removes spaces and other non-digital characters)

number = number.replaceAll("[^0-9]+", ""); //This is the 2nd regex

Output: 1234567890

How can I combine two regular expressions into one, for example, from O / p from the first regular expression to the second.

+4
source share
2 answers

Therefore, you need to remove all non-digit characters and the entire remainder of the line after the first hash or comma character.

You cannot just concatenate patterns using the operator |, because one of the patterns is implicitly fixed at the end of the line.

, , tegex , . DOTALL, .

 (?s)[,#].*$|[^#,0-9]+
+1

.

String number = "(123) (456) (7890)#123";
number = number.replaceAll("[,#](.*)", "").replaceAll("[^0-9]+", "");
+2

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


All Articles