This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes capture string that matches regex Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply locked New topic
Author

capture string that matches regex

Tyler Jordan
Ranch Hand

Joined: Nov 17, 2003
Posts: 70
I'm looking for a way to capture a string out of a larger string that matches a regex. I looked into the String class, but there is nothing there to help. I can't believe a function like this isn't included in the class. I can match on it, but can't extract it:

ie.



Any ideas?
Stevi Deter
Ranch Hand

Joined: Mar 22, 2008
Posts: 265

Tyler,

I think you're looking for the Pattern and Matcher classes. Check the Java Tutorial.

It seems a fine separation of concerns that String doesn't know how to apply regular expressions to itself.


There will always be people who are ahead of the curve, and people who are behind the curve. But knowledge moves the curve. --Bill James
Tyler Jordan
Ranch Hand

Joined: Nov 17, 2003
Posts: 70
Thanks! The function group() from matcher fits the bill.
Alan Moore
Ranch Hand

Joined: May 06, 2004
Posts: 262
Originally posted by Tyler Jordan:
Thanks! The function group() from matcher fits the bill.

But your regex doesn't. The '^' and '$' anchors force the regex to match the entire string, but you obviously want to pluck out matching substrings. Also, there's no need for the "||" (or even "|") in the first character class; OR is implicit, and in fact a pipe just matches a pipe when you use it in a character class. Putting it all together:
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19216

This thread has almost exactly the same question but has some more info, so let's continue there.


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: capture string that matches regex
 
Similar Threads
Panel vs Frame
matcher find() problems
Regex matching
Problem using regular expressions on a SQL where clause to get field names and values
How grab image/graphics/capture of what's behind a frame or window?