0

Hi guys i am trying to figure out a simple regEx from the given text below:

<b>Name:</b> Photomatix.Pro.v4.0.64bit-FOSI<br />

i basically want to output and store only Photomatix.Pro.v4.0.64bit-FOSI i.e. the actual value thats inside the but when i define it like this:

private static final String REG_NAME = "<b>Name:</b>(.*)<br />";

It actually stores and outputs the whole <b>Name:</b> Photomatix.Pro.v4.0.64bit-FOSI<br />

Any ideas on how i can just extract the value given from the above xml text? cheers in advance

2
  • 1
    If you have only XML to parse, you should try an XML parser instead of regexes. Commented Oct 5, 2010 at 10:44
  • I've flagged the "use an XML parser instead" comment as spam/offensive - the question is very explicitly regular expression based, i.e. how to obtain a capturing group. Commented Oct 5, 2010 at 10:52

4 Answers 4

6

This should work:

  final String REG_NAME = "<b>Name:</b>(.*)<br />";

        String text = "<b>Name:</b> Photomatix.Pro.v4.0.64bit-FOSI<br />";

        Pattern pattern = Pattern.compile(REG_NAME);

        Matcher matcher = pattern.matcher(text);

        if (matcher.find()) {
            System.out.println(matcher.group(1));
        }
Sign up to request clarification or add additional context in comments.

3 Comments

group(1) does the trick, group(0) is the complete match, which is equal to the OP's "unexpected" result.
edit: how does it group strings together? i would like to understand the concept of grouping.
1
String r = "/b>(.*)<b";

Pattern p = Pattern.compile( r );
Matcher m = p.matcher( "<b>Name:</b> Photomatix.Pro.v4.0.64bit-FOSI<br />" );

if ( m.find() )
{
  System.out.println( "found: " + m.group(1) );
}

2 Comments

You know full well that your answer is incorrect. It will work for a string like "b>Name:</b Photomatix.Pro.v4.0.64bit-FOSI" which is not what joneey expected. My answer is not perfect either!
indeed, but I think we gave him enough to work with. We can't know all his possible string inputs anyway.
0

(I don't have a Java compiler at hand right now so I cannot verify the answer. Thus this isn't the final answer, but...)

If you really want to do it with regexes, you should take a look at matchers and groups in the Java regex classes.

Comments

0

well, i don't think it is such a good idea to parse an html using regexes, you should use some html java parsers. if you want to use regular expression though, you can check some examples here: Regular Expressions

1 Comment

i wasnt aware their was any html java parsers.

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.