2

I have found this Regex extractor code in C#. Can someone tell me how this works, and how do I write the equivalent in Java?

// extract songtitle from metadata header. 
// Trim was needed, because some stations don't trim the songtitle
fileName = 
    Regex.Match(metadataHeader, 
      "(StreamTitle=')(.*)(';StreamUrl)").Groups[2].Value.Trim();

2 Answers 2

7

This should be what you want.

// Create the Regex pattern
Pattern p = Pattern.compile("(StreamTitle=')(.*)(';StreamUrl)");
// Create a matcher that matches the pattern against your input
Matcher m = p.matcher(metadataHeader);
// if we found a match
if (m.find()) {
    // the filename is the second group. (The `(.*)` part)
    filename = m.group(2);
}
Sign up to request clarification or add additional context in comments.

Comments

1

It pulls "MyTitle" from a string such as "StreamTitle='MyTitle';StreamUrl".

The () operators define match groups, there are 3 in your regex. The second one contains the string of interest, and is gotten in the Groups[2].Value.

There's a few very good regex designers out there. The one I use is Rad Software's Regular Expression Designer (www.radsoftware.com.au). It is very useful for figuring out stuff like this (and it uses C# RegEx's).

Comments

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.