Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex Explanation

Tags:

java

regex

Can someone please explain the meaning of \\A and \\z to me? I am assuming that they have a special meaning in this regular expression because they are being escaped (but I could be wrong and they could just stand for A and z, respectively). Thanks!

private static final Pattern PATTERN = Pattern.compile("\\A(\\d+)\\.(\\d+)\\z");
like image 450
BJ Dela Cruz Avatar asked Sep 19 '12 17:09

BJ Dela Cruz


People also ask

How does regex work in Java?

A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for. A regular expression can be a single character, or a more complicated pattern.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What is mean by \\ s+ in Java?

The plus sign + is a greedy quantifier, which means one or more times. For example, expression X+ matches one or more X characters. Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.

What is the meaning of \\ w in Java?

For example, \d means a range of digits (0-9), and \w means a word character (any lowercase letter, any uppercase letter, the underscore character, or any digit).


1 Answers

\A means "start of string", and \z means "end of string".

You might have seen ^ and $ in this context, but their meaning can vary: If you compile a regex using Pattern.MULTILINE, then they change their meaning to "start of line" and "end of line". The meaning of \A and \z never changes.

There also exists \Z which means "end of string, before any trailing newlines", which is similar to what $ does in multiline mode (where it matches right before the line-ending newline character, if it's there).

like image 81
Tim Pietzcker Avatar answered Sep 28 '22 09:09

Tim Pietzcker