2

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.

3

1 Answer 1

6

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 with P>).

To illustrate both the use of Matcher.group() and Matcher.group(int):

String template = "<P ALIGN=\"LEFT\"><FONT FACE=\"Verdana\" SIZE=\"12\"> My Name is xyz </FONT></P>";
String pattern = "<FONT (.*?)>";

Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(template);

if (m.find()) {
    // prints: <FONT FACE="Verdana" SIZE="12"> My Name is xyz </FONT></P>
    System.out.println(m.group());

    // prints: FACE="Verdana" SIZE="12"
    System.out.println(m.group(1));
}
Sign up to request clarification or add additional context in comments.

15 Comments

Thanks. That is helpful. I have another question. What pattern do i use to match a number in a given input?
For integers? You could use for instance "\\d+".
Thanks. What if there are multiple matches and i want to replace each one with some pattern??
You could use String.replaceAll... it actually takes a regexp as first argument. If you need the matched string, simply refer to it as $0.
i did not get what you are trying to convey. My question again Lets say there were multiple matches and i want to replace each match with a different string, how can i do that?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.