Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression Ends

Tags:

regex

I have scoured the web in the past few hours trying to figure out why in the world one of my colleagues insists on using (?!.) as a last-character in his regular expressions instead of the usual $.

Some of the regular expressions I've seen have been ^.*.txt(?!.) which begin with the usual ^, but do not end with the $. I have not been able to find any definitive or time-efficient reasons, any pros and cons or differences at all?

like image 258
Brainless Box Avatar asked Jun 20 '13 20:06

Brainless Box


People also ask

How do you end a regular expression?

End of String or Line: $ The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions. Multiline option, the match can also occur at the end of a line.

What is regular expression for end of line?

The end of the line is expressed with the dollar sign ($) in the regex. The end of the line will be put at the end of the regex pattern and the required pattern will be specified before the $ sign. The end of the line character is generally used to “line ends with a word, character, characters set, number, etc.”.

How do you start and end a regular expression?

The correct regex to use is ^\d+$. Because “start of string” must be matched before the match of \d+, and “end of string” must be matched right after it, the entire string must consist of digits for ^\d+$ to be able to match.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.


1 Answers

$ may match end of line rather than end of input (this depends on modifiers used). Perhaps this is the reason.

In my opinion, the best way to match the end of input is \z - which means exactly end of input, regardless of modifiers. It is supported in most (if not all) regex implementations.

like image 83
Alex Shesterov Avatar answered Nov 03 '22 02:11

Alex Shesterov