Re: Need help with regular expression
- From: Lars Enderin <lars.enderin@xxxxxxxxx>
- Date: Mon, 26 Feb 2007 12:24:22 GMT
Lars Enderin skrev:
heAzk skrev:Luc Van Bogaert wrote:Hi,
I'm trying to construct a regular expression to check the occurance of
two substrings in a String, but I haven't yet found something that works. Could someone please help?
This is used to parse lines of HTML code.
I'm using String.matches(regex) to find out if the string matches anything like this :
...<!-- %%...%% -->...
The dots can be replaced with anything or even nothing.
This doesn't seem to work :
String.matches(".*" + "<!-- %%" + ".*" + "%% -->"+ ".*")
Thanks,
The '.*' is used to match zero or more occurances of any character. The '*' modifier is greedy however. This means that it'll match as many times as it can. You need to match only zero to three times, which can be accomplished by '.{lower, upper}', so in your case: '.{0,3}'.
I don't think Luc implied that there can be at most three characters between the %%-s, and I don't think that String.matches(regex) is the right method to use. It would be better to use something like
static Pattern commentPtrn = Pattern.compile("<"-- %%(.*?)%% -->");
Remove the extra ": The pattern should be "<-- %%(.*?)%% -->".
.
...
Matcher m;
...
For each line:
m = commentPtrn.matcher(line);
if (m.find()) {
// The pattern exists, and the string between the %%-s is m.group(1).
}
See class Pattern and class Matcher in java.util.regex.
- Follow-Ups:
- Re: Need help with regular expression
- From: Hendrik Maryns
- Re: Need help with regular expression
- References:
- Re: Need help with regular expression
- From: heAzk
- Re: Need help with regular expression
- From: Lars Enderin
- Re: Need help with regular expression
- Prev by Date: Re: Need help with regular expression
- Next by Date: JDIC help
- Previous by thread: Re: Need help with regular expression
- Next by thread: Re: Need help with regular expression
- Index(es):
Relevant Pages
|