A pattern matching an expression that doesn't end with specific sequence - regex

I need a regex pattern which matches such strings that DO NOT end with such a sequence:
\.[A-z0-9]{2,}
by which I mean the examined string must not have at its end a sequence of a dot and then two or more alphanumeric characters.
For example, a string
/home/patryk/www
and also
/home/patryk/www/
should match desired pattern and
/home/patryk/images/DSC002.jpg should not.
I suppose this has something to do with lookarounds (look aheads) but still I have no idea how to make it.
Any help appreciated.

Old Answer
You can use a negative lookbehind at the end if your regex flavor supports it:
^.*+(?<!\.\w{2,})$
This will match a string that has an end anchor not preceded by the icky sequence you don't want.
Note that as m.buettner has pointed out, this uses an indefinite length lookbehind, which is a feature unique to .NET
New Answer
After a bit of digging around, however, I've found that variable length look-aheads are pretty widely supported, so here is a version that uses those:
^(?:(?!\.\w{2,}$).)++$
In a comment on an answer, you have stated you wanted to not match strings with forward slashes at the end, which is accomplished by simply adding a forward slash to the lookahead.
^(?:(?!(\.\w{2,}|/)$).)++$
Note that I am using \w for succinctness, but it lets underscores through. If this is important, you could replace it with [^\W_].

Asad's version is very convenient, but only .NET's regex engine supports variable-length lookbehinds (which is one of the many reasons why every regex question should include the language or tool used).
We can reduce this to a fixed-length lookbehind (which is supported in most engines except for JavaScrpit) if we think about the possible cases which should match. That would be either one or zero letters/digits at the end (whether preceded by . or not) or two or more letters/digits that are not preceded by a dot.
^.*(?:(?<![a-zA-Z0-9])[a-zA-Z0-9]?|(?<![a-zA-Z0-9.])[a-zA-Z0-9]{2,})$

This should do it:
^(?:[^.]+|\.(?![A-Za-z0-9]{2,}$))+$
It alternates between matching one or more of anything except a dot, or a dot if it's not followed by two or more alphanumeric characters and the end of the string.
EDIT: Upgrading it to meet the new requirement is just more of the same:
^(?:[^./]+|/(?=.)|\.(?![A-Za-z0-9]{2,}$))+$
Breaking that down, we have:
[^./]+ # one or more of any characters except . or /
/(?=.) # a slash, as long as there's at least one character following it
\.(?![A-Za-z0-9]{2,}$) # a dot, unless it's followed by two or more alphanumeric characters followed by the end of the string
On another note: [A-z] is an error. It matches all the uppercase and lowercase ASCII letters, but it also matches the characters [, ], ^, _, backslash and backtick, whose code points happen to lie between Z and a.

Variable length look behinds are rarely supported, but you don't need one:
^.*(?<!\.[A-z0-9][A-z0-9]?)$

Related

Invalid Boost Regex Lookbehind with OR and ^

I'm having an issue with boost regex and suspect its a bug, but knew someone here would know for sure and if there's a workaround
I'm checking the start of a selection for start of string, white-space or an underscore using
(?<=^|\s|_)
However under boost this creates an error:
ERROR: Bad regular expression at char 0. Invalid lookbehind assertion encountered in the regular expression.
Without the ^, all is well and similarly with just the ^ its fine.
Any help getting around this would be greatly received.
Cheers
Brief
The code you presented (?<=^|\s|_) is a lookbehind using 3 possibilities:
^ Assert position at start of the line
\s Match any whitespace character
_ Match the underscore character literally
Note that with the above, 2. and 3. are identical in the number of characters that it will match: One, while 1. will match zero characters (position assertion).
Since 1. is of width 0, and 2. and 3. are of width 1, this causes the lookbehind to be of variable width. Some regex flavours will permit subtleties such as assertions to be used alongside fixed width matches, while others will not.
Typically, in lookbehinds, any quantifiers or variations thereof where matches don't share the same length (variable length) causes errors as you've seen.
Solution
Some regex flavours will permit your code to run, while others will not. For regex flavours that do not permit this sort of behaviour, workarounds should be used.
For your specific case, you can likely use the following regex to solve your issue
(?:^|(?<=\s|_))
Boost regex, like Python re, does not allow you to use alternatives of different length in a lookbehind (^ matches zero chars, while \s and _ match 1 char both). See the Boost reference:
(?<=pattern) consumes zero characters, only if pattern could be matched against the characters preceding the current position (pattern must be of fixed length).
In these cases, it is a good idea to use a negative lookbehind with a negated character class matching any char but the ones you need. The (?<=^|\s|_) pattern will change into
(?<![^\s_])
It will match any location that is not immediately preceded with a char other than whitespace or _ (i.e. it will match the start of string (^), after a whitespace or _, just what you need).
See the regex demo:

RegEx: Non-repeating patterns?

I'm wrestling with how to write a specific regex, and thought I'd come here for a little guidance.
What I'm looking for is an expression that does the following:
Character length of 7 or more
Any single character is one of four patterns (uppercase letters, lowercase letters, numbers and a specific set of special characters. Let's say #$%#).
(Now, here's where I'm having problems):
Another single character would also match with one of the patterns described above EXCEPT for the pattern that was already matched. So, if the first pattern matched is an uppercase letter, the second character match should be a lowercase letter, number or special character from the pattern.
To give you an example, the string AAAAAA# would match, as would the string AAAAAAa. However, the string AAAAAAA, nor would the string AAAAAA& (as the ampersand was not part of the special character pattern).
Any ideas? Thanks!
If you only need two different kinds of characters, you can use the possessive quantifier feature (available in Objective C):
^(?:[a-z]++|[A-Z]++|[0-9]++|[#$%#]++)[a-zA-Z0-9#$%#]+$
or more concise with an atomic group:
^(?>[a-z]+|[A-Z]+|[0-9]+|[#$%#]+)[a-zA-Z0-9#$%#]+$
Since each branch of the alternation is a character class with a possessive quantifier, you can be sure that the first character matched by [a-zA-Z0-9#$%#]+ is from a different class.
About the string size, check it first separately with the appropriate function, if the size is too small, you will avoid the cost of a regex check.
First you need to do a negative lookahead to make sure the entire string doesn't consist of characters from a single group:
(?!(?:[a-z]*|[A-Z]*|[0-9]*|[#$%#]*)$)
Then check that it does contain at least 7 characters from the list of legal characters (and nothing else):
^[a-zA-Z0-9#$%#]{7,}$
Combining them (thanks to Shlomo for pointing that out):
^(?!(?:[a-z]*|[A-Z]*|[0-9]*|[#$%#]*)$)[a-zA-Z0-9#$%#]{7,}$

What does (^?)* mean in this regex?

I have this regex:
^(^?)*\?(.*)$
If I understand correctly, this is the breakdown of what it does:
^ - start matching from the beginning of the string
(^?)* - I don't know know, but it stores it in $1
\? - matches a question mark
(.*)$ - matches anything until the end of the string
So what does (^?)* mean?
The (^?) is simply looking for the literal character ^. The ^ character in a regex pattern only has special meaning when used as the first character of the pattern or the first character in a grouping match []. When used outside those 2 positions the ^ is interpreted literally meaning in looks for the ^ character in the input string
Note: Whether or not ^ outside of the first and grouping position is interpreted literally is regex engine specific. I'm not familiar enough with LUA to state which it does
Lua does not have a conventional regexp language, it has Lua patterns in its place. While they look a lot like regexp, Lua patterns are a distinct language of their own that has a simpler set of rules and most importantly lacks grouping and alternation features.
Interpreted as a Lua pattern, the example will surprising a longtime regexp user since so many details are different.
Lua patterns are described in PiL, and at a first glance are similar enough to a conventional regexp to cause confusion. The biggest differences are probably the lack of an alternation operator |, parenthesis are only used to mark captures, quantifiers (?, -, +, and *) only apply to a character or character class, and % is the escape character not \. A big clue that this example was probably not written with Lua in mind is the lack of the Lua pattern quoting character % applied to any (or ideally, all) of the non-alphanumeric characters in the pattern string, and the suspicious use of \? which smells like a conventional regexp to match a single literal ?.
The simple answer to the question asked is: (^?)* is not a recommended form, and would match ^* or *, capturing the presence or absence of the caret. If that were the intended effect, then I would write it as (%^?)%* to make that clearer.
To see why this is the case, let's take the pattern given and analyze it as a Lua pattern. The entire pattern is:
^(^?)*\?(.*)$
Handed to string.match(), it would be interpreted as follows:
^ anchors the match to the beginning of the string.
( marks the beginning of the first capture.
^ is not at the beginning of the pattern or a character class, so it matches a literal ^ character. For clarity that should likely have been written as %^.
? matches exactly zero or one of the previous character.
) marks the end of the first capture.
* is not after something that can be quantified so it matches a literal * character. For clarity that should likely have been written as %*.
\ in a pattern matches itself, it is not an escape character in the pattern language. However, it is an escape character in a Lua short string literal, making the following character not special to the string literal parser which in this case is moot because the ? that follows was not special to it in any case. So if the pattern were enclosed in double or single quotes, then the \ would be absorbed by string parsing. If written in a long string (as [[^(^?)*\?(.*)$]], the backslash would survive the string parser, to appear in the pattern.
? matches exactly zero or one of the previous character.
( marks the beginning the second capture.
. matches any character at all, effectively a synonym for the class [\000-\255] (remember, in Lua numeric escapes are in decimal not octal as in C).
* matches zero or more of the previous character, greedily.
) marks the end of the second capture.
$ anchors the pattern to the end of the string.
So it matches and captures an optional ^ at the beginning of the string, followed by *, then an optional \ which is not captured, and captures the entire rest of the string. string.match would return two strings on success (either or both of which might be zero length), or nil on failure.
Edit: I've fixed some typos, and corrected an error in my answer, noticed by Egor in a comment. I forgot that in patterns, special symbols loose their specialness when in a spot where it can't apply. That makes the first asterisk match a literal asterisk rather than be an error. The cascade of that falls through most of the answer.
Note that if you really want a true regexp in Lua, there are libraries available that will provide it. That said, the built-in pattern language is quite powerful. If it is not sufficient, then you might be best off adopting a full parser, and use LPeg which can do everything a regexp can and more. It even comes with a module that provides a complete regexp syntax that is translated into an LPeg grammar for execution.
In this case, the (^?) refers to the previous string "^" meaning the literal character ^ as Jared has said. Check out regexlib for any further deciphering.
For all your Regex needs: http://regexlib.com/CheatSheet.aspx
It looks to me like the intent of the creator of the expression was to match any number of ^ before the question mark, but only wanted to capture the first instance of ^. However, it may not be a valid expression depending on the engine, as others have stated.

Regex doesn't recognize underscore as special character

/(?=^.{8,}$)(?=.*[_!##$%^&*-])(?=.*\d)(?=.*\W+)(?![.\n])(?=.*[a-z])(?=.*[A-Z]).*$/
I'm trying to make a regex for password validation such that the password must be at least 8 chars and include one uppercase, one lowercase, one number, and one special char. It works fine except it won't recognize the underscore (_) as a special character. I.e., Pa$$w0rd matches, but Pass_w0rd doesn't. Thoughts?
This portion of the regex seems to be looking for special characters:
(?=.*[!##$%^&*-])
Note that the character class does not include an underscore, try changing this to the following:
(?=.*[_!##$%^&*-])
You will also need to modify or remove this portion of the regex:
(?=.*\W+)
\W is equivalent to [^a-zA-Z0-9_], so if an underscore is your only special character this portion of the regex will cause it to fail. Instead, change it to the following (or remove it, it is redundant since you already check for special characters earlier):
(?=.*[^\w_])
Complete regex:
/(?=^.{8,}$)(?=.*[_!##$%^&*-])(?=.*\d)(?=.*[^\w_])(?![.\n])(?=.*[a-z])(?=.*[A-Z]).*$/
This one here works as well. It defines a special character as by excluding alphanumerical characters and whitespace, so it includes the underscore:
(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[\d])(?=.*?[^\sa-zA-Z0-9]).{8,}
The problem is that the only thing that could possibly satisfy the \W, by definition, is something other than [a-zA-Z0-9_]. The underscore is specifically not matched by \W, and in Pass_w0rd, nothing else is matched by it, either.
I suspect that having both your specific list of special characters and the \W is overkill. Pick one and you're likely to be happier. I also recommend splitting this whole thing up into several separate tests for much better maintainability.
A much simpler regex that works for you is this:
/(?=.*[_!##$%^&*-])(?=.*\d)(?!.*[.\n])(?=.*[a-z])(?=.*[A-Z])^.{8,}$/
There were few mistakes in your original regex eg:
You don't need to use lookahead for making sure there are 8 chars in input
negative lookahead [.\n] was missing .*
(?=.*\W+) is superfluous and probably not serving any purpose

URL Regular Expression matching exact 3 characters after decimal

I require regular expression to match exactly 3 or 2 characters after decimal point, so that it validates www.xyz.com and not xyz.Complete
I think what you want is \b
I can't think of a case that's not reasonably covered by using the word-boundary assertion \b any of the other answers need only have \b at the end (if it's always .com, then you'd use .com\b which means essentially a literal dot (.) character followed by com, where whatever follows is something other than a letter, number or underscore. It's a zero-width assertion, which means it will not capture anything. To allow a .net or .edu as well, you would use \.(com|edu|net)\b
The \b assertion is supported in most tools and languages using regexes, but if you need to get more precise (for instance, you might want to allow an underscore after com), your tool or language compiler may support "lookaheads" which are also zero-width assertions. (in the instance mentioned just above, you would use something like \.(com|net|edu|org|mil|museum)(?![a-zA-Z0-9]) which would prohibit numbers and uppercase or lowercase letters)
Strictly answering your question of
match exactly 3 or 2 characters after decimal point
To match just the ending:
\.[A-Za-z]{2,3}$
the \ escapes the . which otherwise means "any character"
You forgot the string beginning and ending checks (^, $). Use this:
^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU)$