I have a string and a pattern that I want to search for in that string. Now, when I match the pattern in the string, I want to know the string that matches my pattern.
String template = "<P ALIGN=\"LEFT\"><FONT FACE=\"Verdana\" SIZE=\"12\"> My Name is xyz </FONT></P>";
String pattern = "<FONT.*>";
Pattern.compile(pattern,Pattern.CASE_INSENSITIVE);
How can I find out the string that matches the pattern in my template.
i.e I want to get <FONT FACE=\"Verdana\" SIZE=\"12\"> as the result. Is there any method provided by the regex library in Java which can help me?
Update:
What is the regular expression that can match <FONT FACE=\"Verdana\" SIZE=\"12\"> My Name is xyz </FONT> and <LI><FONT FACE=\"Verdana\" SIZE=\"12\"> My Name is xyz </FONT></LI> and it should not be greedy in a given text.
You can access the matched part of the string through
matcher.group().A more elaborate way is to use capturing groups. Put the part you want to “extract” from the matched string within parethesis, and then get hold of the matched part through, for instance
matcher.group(1).In your particular example, you need to use a reluctant qualifier for the
*. Otherwise, the.*will match all the way to the end of the string (since it ends withP>).To illustrate both the use of
Matcher.group()andMatcher.group(int):