Carets (^) in regular expressions

A

Alan

The Java SE 6.0 API documentation for the Pattern class in
java.util.regex says the caret ("^") can be used in a regular
expression to find the beginning of a line. However, it can also be
used to denote negation (see "Character classes" section). How does
Java tell the difference in this usage?

Thanks, Alan
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Alan said:
The Java SE 6.0 API documentation for the Pattern class in
java.util.regex says the caret ("^") can be used in a regular
expression to find the beginning of a line. However, it can also be
used to denote negation (see "Character classes" section). How does
Java tell the difference in this usage?

Java regex does what other regex does: ^ outside [] is start and
^ inside [] is negation.

Arne
 
A

Alan

Arne,
Thanks. This is the first regexp I`ve used. It turns out my
problem was using "^\p" instead of the correct "\P".

Alan
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Alan said:
Thanks. This is the first regexp I`ve used. It turns out my
problem was using "^\p" instead of the correct "\P".

You could also have used ^ just inside [].

Try running:

import java.util.regex.Pattern;

public class R {
public static void main(String[] args) {
System.out.println(Pattern.matches("\\p{Digit}+", "123"));
System.out.println(Pattern.matches("\\p{Digit}+", "ABC"));
System.out.println(Pattern.matches("\\P{Digit}+", "123"));
System.out.println(Pattern.matches("\\P{Digit}+", "ABC"));
System.out.println(Pattern.matches("[^\\p{Digit}]+", "123"));
System.out.println(Pattern.matches("[^\\p{Digit}]+", "ABC"));
}
}

Arne
 

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

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,267
Latest member
WaylonCogb

Latest Threads

Top