Re: Extracting substring with regexp
- From: Eric Sosman <Eric.Sosman@xxxxxxx>
- Date: Thu, 31 Jan 2008 16:09:20 -0500
Alex wrote:
How to extract substring with regexp when we have start and end for
substring?
For example I want to find what is between "abc" and "xyz" in the
String.
Pattern p = Pattern.compile("abc*xyz");
Matcher m = p.matcher("aaaaaaaaaabc123xyzzzzzzzzzzzzz");
but m.matches() returns false and can't find my patter.
How can I get these "123" in this example?
First, correct your regexp: As written, it looks for
an a, a b, any number of c's (including zero), then x,
y, and z. You probably want "abc.*xyz" instead.
Second, realize that matches() tries to match the
entire input sequence. So it will fail, because the "aa"
at the start does not match either the original or the
corrected regexp. You probably want the find() method
instead.
Third, since what you are interested is the stuff
between the abc and the xyz, you should indicate your
interest by making that part into a "group." Change the
regexp yet again, this time to "abc(.*)xyz". When find()
returns true, you can then use m.group(1) to retrieve the
part between the parentheses.
Finally, it would be a Really Good Idea for you to read
the Javadoc on the Pattern and Matcher classes, where all
this and more is described, with reasonably comprehensible
examples, too.
--
Eric.Sosman@xxxxxxx
.
- Follow-Ups:
- Re: Extracting substring with regexp
- From: Alex
- Re: Extracting substring with regexp
- References:
- Extracting substring with regexp
- From: Alex
- Extracting substring with regexp
- Prev by Date: Re: Extracting substring with regexp
- Next by Date: Re: Extracting substring with regexp
- Previous by thread: Re: Extracting substring with regexp
- Next by thread: Re: Extracting substring with regexp
- Index(es):