Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use \A in a regex?

Tags:

regex

End of line anchor $ match even there is extra trailing \n in matched string, so we use \Z instead of $

For example

^\w+$ will match the string abcd\n but ^\w+\Z is not

How about \A and when to use?

like image 882
YOU Avatar asked Apr 16 '10 04:04

YOU


People also ask

What is \A in regex?

\A Matches the beginning of the string. \z Matches the end of the string. \Z Matches the end of the string unless the string ends with a "\n" , in which case it matches just before the "\n" . So, use \A and lowercase \z . If you use \Z someone could sneak in a newline character.

What is the difference between \b and \b in regular expression?

Using regex \B-\B matches - between the word color - coded . Using \b-\b on the other hand matches the - in nine-digit and pass-key .

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


2 Answers

Most often it's used when also enabling multi-line matches. Since \A only matches at the beginning of the ENTIRE text, as opposed to just a line beginning, in regexes that can match across lines the functionality of ^ and \A are different.

like image 109
Amber Avatar answered Oct 01 '22 10:10

Amber


As with any regex feature, you use it when it more exactly describes what you need as opposed to any more general feature. If you know that you want to match exactly at the start of a string (instead of logical lines), use the regex feature that describes that. Don't use regex features that could possibly match in situations that you don't want.

For Perl, see the perlre docs for details about the zero-width assertions:

\b  Match a word boundary
\B  Match except at a word boundary
\A  Match only at beginning of string
\Z  Match only at end of string, or before newline at the end
\z  Match only at end of string
\G  Match only at pos() (e.g. at the end-of-match position
    of prior m//g)
like image 34
brian d foy Avatar answered Oct 01 '22 10:10

brian d foy