Re: Need help with regular expression



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.
.



Relevant Pages

  • Re: Need help with regular expression
    ... two substrings in a String, but I haven't yet found something that works. ... I'm using String.matches(regex) to find out if the string matches anything like this: ... See class Pattern and class Matcher in java.util.regex. ...
    (comp.lang.java.help)
  • Re: Need help with regular expression to parse URLs
    ... The matcher gives me 1 group with this value: ... You can get the individual elements with smaller capturing groups: ... What you can do is make a regexp which matches a single occurrence of a pair of elements, and then use the Matcher's findmethod to loop over all occurrences in the string. ... URI uri = new URI; ...
    (comp.lang.java.programmer)
  • Re: Prefixes of regular expressions
    ... prefix. ... Match the supplied string against the first; ... If matched, display ... For some situations you could probably use groupCounton the Matcher ...
    (comp.lang.java.programmer)
  • Re: Java regex syntax
    ... I see that Matcher takes a CharSequence, not a String, but String implements CharSequence. ... I actually know my way around regexes reasonably well; the problem was in the translation to the Java idiom. ...
    (comp.lang.java.programmer)
  • Is matching against several regexs so clumsy?
    ... I'd like to search for several regex's in a String, ... position is set position=macherObject.endwhenever a regex is found. ... The only way I found was to create a Pattern and a Matcher for each ... public static void main{ ...
    (comp.lang.java.programmer)