Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Regular Expression to extract numbers in brackets

Tags:

java

regex

Currently, I am struggling with the problem of catching numbers with REGEX by using Java

The string which I am trying to catch the numbers in this string value using REGEX is this..

[TEST][64894]HelloWorld[KGMObilians]

My wish is to catch the numbers which are located in [ ].

Would this be possible with Java? I could easily take the number by splitting the string, but the company wants me to use the regex since it is more safer and faster. please help me.

like image 439
홍성호 Avatar asked Oct 31 '22 13:10

홍성호


1 Answers

Try this:

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

IDEONE DEMO

And if you dont want the brackets then simply make 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

like image 187
Rahul Tripathi Avatar answered Nov 15 '22 05:11

Rahul Tripathi