Reputation: 16777
Pattern pattern = Pattern.compile("<a>([a-zA-Z]+)</a>")
Matcher matcher = pattern.matcher("<a>Text</a>");
matcher.find()
String str = matcher.group();
I want to get "Text"
to str, but I get "<a>Text</a>"
. Why and how should I do it properly?
Upvotes: 3
Views: 301
Reputation: 17238
you have to call matcher.group
with the number of your capture group - if you omit the argument the complete match will be returned.
best regards, carsten
ps: the best address to quickly solve these kinds of question is to look up the repective part of the java api docs.
Upvotes: 2
Reputation: 14366
group()
returns the entire matched text. You want group(1)
, which returns the first paren-delimited group within the match. See the API docs.
Upvotes: 2
Reputation: 160261
You want group(1)
; the first group is the entire pattern.
See the group() and group(int) docs.
Upvotes: 2
Reputation: 28069
There is another overload of group() on matcher. Try:
matcher.group(1);
Upvotes: 2
Reputation: 225064
You need to specify the index of the group, 1 in this case:
Pattern pattern = Pattern.compile("<a>([a-zA-Z]+)</a>")
Matcher matcher = pattern.matcher("<a>Text</a>");
matcher.find()
String str = matcher.group(1);
Documentation for Matcher.group(int)
Upvotes: 4
Reputation: 183456
matcher.group()
, with no arguments, returns the entire matched substring. Use matcher.group(1)
to retrieve just the contents of the first parenthesized capture-group:
Pattern pattern = Pattern.compile("<a>([a-zA-Z]+)</a>")
Matcher matcher = pattern.matcher("<a>Text</a>");
matcher.find();
String str = matcher.group(1);
Upvotes: 5