Bookmark Topic Watch Topic
  • New Topic

capture string that matches regex  RSS feed

 
Tyler Jordan
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Report post to moderator
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.
 
Tyler Jordan
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Report post to moderator
Thanks! The function group() from matcher fits the bill.
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Report post to moderator
This thread has almost exactly the same question but has some more info, so let's continue there.
 
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!