Use regex to extract numbers in parentheses

I am currently struggling with the problem of catching numbers with REGEX using Java

The string I'm trying to catch the numbers in this string value using REGEX is ..

[TEST][64894]HelloWorld[KGMObilians] 

My desire is to catch the numbers that are in [].

Is this possible with Java? I could easily take the number by dividing the string, but the company wants me to use the regex as it is safer and faster. please, help.

+5
source share
2 answers

Try the following:

 String s = "[TEST][64894]HelloWorld[KGMObilians]"; Pattern patt = Pattern.compile("\\[\\d+\\]"); Matcher match = patt.matcher(s); 

IDEONE DEMO

And if you don't need parentheses just do it like

 String s = "[TEST][64894]HelloWorld[KGMObilians]"; Pattern patt = Pattern.compile("\\[(\\d+)\\]"); Matcher match = patt.matcher(s); while(match.find()){ System.out.println(match.group(1)); } 

IDEONE DEMO

+2
source

He takes a number from a string.

  String s = "[TEST][64894]HelloWorld[KGMObilians]"; Pattern patt = Pattern.compile("\\[\\d+\\]"); Matcher match = patt.matcher(s); if (match.find()) { String group = match.group(); System.out.println(group.replaceAll("\\[|\\]", "")); } 
0
source

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


All Articles