RegEx Woes! Please Help, Simple Question

S

Saad Malik

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

Alan Krueger

Saad said:
([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.
 
S

Sharp

Saad said:
([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
 
J

John C. Bollinger

Sharp said:
Saad said:
([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?

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top