Hi Guys/Gals
I got a quick question on regex. My input string consists of two
characters: [a-z][a-z].. However, I only want to match if the two
characters are different.
Example: ab,ck,dk,gk... are all valid, but aa,bb,cc,dd,ee... should not
match..
This is the regex I have so far, but it does not seem to work:
([a-z])(?!\1)[a-z]
complete program:
Pattern pat2 = Pattern.compile("([a-z])(?!\1)[a-z]");
Matcher m = pat2.matcher("aa");
System.out.println(m.matches()); THIS PRINTS TRUE but aa should not be
true.
Thanks in Advance,
Saad.
Alan Krueger - 02 May 2005 02:02 GMT
> ([a-z])(?!\1)[a-z]
Try two backslashes. One backslash is interpreted by the Java compiler,
so you'll need to quote it with another so it makes it to the regular
expression compiler.
Saad Malik - 02 May 2005 02:10 GMT
You are a genius! It worked.
Thanks,
Saad
Sharp - 02 May 2005 13:02 GMT
> > ([a-z])(?!\1)[a-z]
>
> Try two backslashes. One backslash is interpreted by the Java compiler,
> so you'll need to quote it with another so it makes it to the regular
> expression compiler.
What does the '?' mean?
Cheers
Sharp
Thomas Schodt - 02 May 2005 15:23 GMT
>>>([a-z])(?!\1)[a-z]
> What does the '?' mean?
Non-capturing groups are described just before backslashes
<http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html#bs>
John C. Bollinger - 02 May 2005 17:06 GMT
>>>([a-z])(?!\1)[a-z]
>>
[quoted text clipped - 3 lines]
>
> What does the '?' mean?
The "(?!" introduce a "zero-width negative lookahead assertion", which
is closed by a matching ")". See the Pattern API docs for more on
Java's regex syntax, although it's fairly standard. For details on the
_meaning_ of this sort of thing, Google for tutorials on regexes.

Signature
John Bollinger
jobollin@indiana.edu