Reputation: 2436
In a line I may have (123,456)
I want to find it using pattern in java. What I did is:
Pattern pattern = Pattern.compile("\\W");
Matcher matcher = pattern.matcher("(");
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end() + " ");
}
Input: This is test (123,456)
Output:Start index: 0 End index: 1 (
Why??
Upvotes: 0
Views: 909
Reputation: 2717
I am not sure how \W
is going to match it. \W
matches a non word character.
You will also have to escape those backslashes.
Round brackets need to be escaped , as by default they are used for grouping.
Maybe the regex you meant was
Pattern pattern = Pattern.compile("\\([,\\d]+\\)");
Matcher matcher = pattern.matcher(inputString);
while (matcher.find()) {
String matched = matcher.group();
//Do something with it
}
Explanation:
\\( # Match (
[,\\d]+ # Match 1+ digits/commas. Don't be surprised if it matches (,,,,,,)
\\) # Match )
Upvotes: 4
Reputation: 425043
To do it in one line:
String num = str.replaceAll(".*\\(([\\d,]+)\\).*", "$1");
Upvotes: 1