What does this regex expression mean? - python

I am very weak at regular expressions, now I'm debugging some code, the code is searching strings with an expression like:
r"coding[:=]\s*([-\w.]+)"
What kind of string does it search for?
To me, it seems to match something like:
coding= xxxxx
but I don't know the exact meaning of the mystery character. Can anyone explain in a bit more detail?

Let's break this down:
coding: literal text match, only the word "coding" will do
[:=]: character group, either a colon ":" or an equals sign "=" matches
\s*: 0 or more whitespace characters; spaces and tabs, but could match newlines too if so configured.
(..): a matching group, the contents will be available as a match group for further processing.
[-\w.]+: one or more characters in the group, matching a dash "-", a dot "." or any word character; \w is a character class usually matching the letters 'a' through 'z' (upper and lowercase), numbers '0' up to '9' and the underscore "_".
If you switch on unicode support (on by default in Python 3) the \w class captures a lot more though. Any character classified as an alphanumeric in the Unicode database would match.
Examples of matches:
"coding=foobar320_42spam_eggs", group would be foobar320_42spam_eggs
"coding: something-or-other", group would be something-or-other
"coding: whatever.42", group would be whatever.42

It will match the following:
coding + one of : or = + zero or more spaces (\s = space, tab, any whitespace char) + some text, that may also contain . and -.

Sample Expressions for your Regular Expression http://rubular.com/r/cqE6HTD8Vb

Related

Regular Expression in Python strings

I want to validate a string that satisfies the below three conditions using regular expression
The special characters allowed are (. , _ , - ).
Should contain only lower-case characters.
Should not start or end with special character.
To satisfy the above conditions, I have created a format as below
^[^\W_][a-z\.,_-]+
This pattern works fine up to second character. However, this pattern is failing for the 3rd and subsequent characters if those contains any special character or upper cases characters.
Example:
Pattern Works for the string S#yanthan but not for Sa#yanthan. I am expecting that pattern to pass even if the third and subsequent characters contains any special characters or upper case characters. Can you suggest me where this pattern goes wrong please? Below is the snippet of the code.
import re
a = "Sayanthan"
exp = re.search("^[^\W_][a-z\.,_-]+",a)
if exp:
print(True)
else:
print(False)
Based on you initial rules I'd go with:
^[a-z](?:[.,_-]*[a-z])*$
See the online demo.
However, you mentioned in the comments:
"Also the third condition is "should not start with Special character" instead of "should not start or end with Special character""
In that case you could use:
^[a-z][-.,_a-z]*$
See the online demo
The pattern that you tried ^[^\W_][a-z.,_-]+ starts with [^\W_] which will match any word char except an underscore, so it could also be an uppercase char.
Then [a-z.,_-]+ will match 1+ times any of the listed, which means the string can also end with a comma for example.
Looking at the conditions listed, you could use:
^[a-z](?:[a-z.,_-]*[a-z])?\Z
^ Start of string
[a-z] Match a lower case char a-z
(?: Non capture group
[a-z.,_-]*[a-z] Match 0+ occurrences of the listed ending with a-z
)? Close group and make it optional
\Z End of string
Regex demo

Python regex specific word with singe quote at end

Searching a large syslog repo and need to get a specific word to match with a certain condition.
I'm using regex to compile a search for this word. I've read the python docs on regex characters and I understand how to specify each criteria separately but somehow missing how to concatenate all together for my specific search. This is what I have so far but not working...
p = re.compile("^'[A-Z]\w+'$")
match = re.search(p, syslogline, )
the word is a username that can be alphanum, always beginning with an uppercase character (preceded by blank space), can contain chars or nums, is 3-12 in length and ends with single quote.
an example would be: Epresley01' or J98473'
Brief
Based on your requirements (also stated below), your regex doesn't work because:
^' Asserts the position at the start of the line and ensures a ' is the first character of that line.
$ Asserts the position at the end of the line.
Having said that you specify that it's preceded by a space character (which isn't present in your pattern). You pattern also checks for ' which isn't the first character of the username. Given that you haven't actually given us a sample of your file I can't confirm nor deny that your string starts before the username and ends after it, but if that's not the case the anchors ^$ are also not helping you here.
Requirements
The requirements below are simply copied from the OP's question (rewritten) to outline the username format. The username:
Is preceded by a space character.
Starts with an uppercase letter.
Contains chars or nums. I'm assuming here that chars actually means letters and that all letters in the username (including the uppercase starting character) are ASCII.
Is 3-12 characters in length (excluding the preceding space and the end character stated below).
Ends with an apostrophe character '.
Code
See regex in use here
(?<= )[A-Z][^\W_]{2,11}'
Explanation
(?<= ) Positive lookbehind ensuring what precedes is a space character
[A-Z] Match any uppercase ASCII letter
[^\W_]{2,11} Match any word character except underscore _ (equivalent to a-zA-Z0-9)
This appears a little confusing because it's actually a double-negative. It's saying match anything that's not in the set. The \W matches any non-word character. Since it's a double-negative, it's like saying don't match non-word characters. Adding _ to the set negates it.
' Match the apostrophe character ' literally
I think you can do it like this:
(Updated after the comment from #ctwheels)
See regex in use here
[A-Z][a-zA-Z0-9]{1,10}'
Explanation
Match a whitespace
Match an uppercase character [A-Z]
Match [a-zA-Z0-9]+
Match an apostrophe '
Demo

Regular expression for letters, dash, underscore, numbers, and space

This is my attempt
def matcher(ex):
if re.match(r'^[\w|\d][A-Za-z0-9_-]+$', ex):
print 'yes'
My goal is to match only submission that satisfy all the followings
begins with only a letter or a numeric digit, and
only letter, space, dash, underscore and numeric digit are allowed
all ending spaces are stripped
In my regex, matcher('__') is considered valid. How can I modify to achieve what I want really want? I believe \w also includes underscore. But matcher('_') is not matched...
def matcher(ex):
ex = ex.rstrip()
if re.match(r'^[a-zA-Z0-9][ A-Za-z0-9_-]*$', ex):
print 'yes'
Problems in your original regex:
| doesn't mean alternation in a character class, it means a pipe character literally.
You used + for your following characters, meaning one or more, so a one-character string like '_' wouldn't match.
You used \w in your first character, which accepted underscores.

In regex, what does [\w*] mean?

What does this regex mean?
^[\w*]$
Quick answer: ^[\w*]$ will match a string consisting of a single character, where that character is alphanumeric (letters, numbers) an underscore (_) or an asterisk (*).
Details:
The "\w" means "any word character" which usually means alphanumeric (letters, numbers, regardless of case) plus underscore (_)
The "^" "anchors" to the beginning of a string, and the "$" "anchors" To the end of a string, which means that, in this case, the match must start at the beginning of a string and end at the end of the string.
The [] means a character class, which means "match any character contained in the character class".
It is also worth mentioning that normal quoting and escaping rules for strings make it very difficult to enter regular expressions (all the backslashes would need to be escaped with additional backslashes), so in Python there is a special notation which has its own special quoting rules that allow for all of the backslashes to be interpreted properly, and that is what the "r" at the beginning is for.
Note: Normally an asterisk (*) means "0 or more of the previous thing" but in the example above, it does not have that meaning, since the asterisk is inside of the character class, so it loses its "special-ness".
For more information on regular expressions in Python, the two official references are the re module, the Regular Expression HOWTO.
As exhuma said, \w is any word-class character (alphanumeric as Jonathan clarifies).
However because it is in square brackets it will match:
a single alphanumeric character OR
an asterisk (*)
So the whole regular expression matches:
the beginning of a
line (^)
followed by either a
single alphanumeric character or an
asterisk
followed by the end of a
line ($)
so the following would match:
blah
z <- matches this line
blah
or
blah
* <- matches this line
blah
\w refers to 0 or more alphanumeric characters and the underscore. the * in your case is also inside the character class, so [\w*] would match all of [a-zA-Z0-9_*] (the * is interpreted literally)
See http://www.regular-expressions.info/reference.html
To quote:
\d, \w and \s --- Shorthand character classes matching digits, word characters, and whitespace. Can be used inside and outside character classes.
Edit corrected in response to comment
From the beginning of this line, "Any number of word characters (letter, number, underscore)" until the end of the line.
I am unsure as to why it's in square brackets, as circle brackets (e.g. "(" and ")") are correct if you want the matched text returned.
\w is equivalent to [a-zA-Z0-9_] I don't understand the * after it or the [] around it, because \w already is a class and * in class definitions makes no sense.
As said above \w means any word. so you could use this in the context of below
view.aspx?url=[\w]
which means you can have any word as the value of the "url=" parameter

Looking for a regular expression including alphanumeric + "&" and ";"

Here's the problem:
split=re.compile('\\W*')
This regular expression works fine when dealing with regular words, but there are occasions where I need the expression to include words like k&auml;ytt&auml;j&aml;auml;.
What should I add to the regex to include the & and ; characters?
I would treat the entities as a unit (since they also can contain numerical character codes), resulting in the following regular expression:
(\w|&(#(x[0-9a-fA-F]+|[0-9]+)|[a-z]+);)+
This matches
either a word character (including “_”), or
an HTML entity consisting of
the character “&”,
the character “#”,
the character “x” followed by at least one hexadecimal digit, or
at least one decimal digit, or
at least one letter (= named entity),
a semicolon
at least once.
/EDIT: Thanks to ΤΖΩΤΖΙΟΥ for pointing out an error.
You probably want to take the problem reverse, i.e. finding all the character without the spaces:
[^ \t\n]*
Or you want to add the extra characters:
[a-zA-Z0-9&;]*
In case you want to match HTML entities, you should try something like:
(\w+|&\w+;)*
you should make a character class that would include the extra characters. For example:
split=re.compile('[\w&;]+')
This should do the trick. For your information
\w (lower case 'w') matches word characters (alphanumeric)
\W (capital W) is a negated character class (meaning it matches any non-alphanumeric character)
* matches 0 or more times and + matches one or more times, so * will match anything (even if there are no characters there).
Looks like this RegEx did the trick:
split=re.compile('(\\\W+&\\\W+;)*')
Thanks for the suggestions. Most of them worked fine on Reggy, but I don't quite understand why they failed with re.compile.

Categories