What difference does round brackets in regular expression make? [duplicate] - python

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 4 years ago.
I am currently going through pythonchallenge.com, and now trying to make a code that searches for a lowercase letter with exactly three uppercase letters on both side of it. Then I got stuck on trying to make a regular expression for it. This is what I have tried:
import re
#text is in https://pastebin.com/pAFrenWN since it is too long
p = re.compile("[^A-Z]+[A-Z]{3}[a-z][A-Z]{3}[^A-Z]+")
print("".join(p.findall(text)))
This is what I got with it:
dqIQNlQSLidbzeOEKiVEYjxwaZADnMCZqewaebZUTkLYNgouCNDeHSBjgsgnkOIXdKBFhdXJVlGZVme
gZAGiLQZxjvCJAsACFlgfe
qKWGtIDCjn
I later searched for the solution, which had this regular expression:
p = re.compile("[^A-Z]+[A-Z]{3}([a-z])[A-Z]{3}[^A-Z]+")
So there is a bracket around [a-z], and I couldn't figure out what difference it makes. I would like some explanation on this.

Use Parentheses for Grouping and Capturing By placing part of a
regular expression inside round brackets or parentheses, you can group
that part of the regular expression together. This allows you to apply
a quantifier to the entire group or to restrict alternation to part of
the regex.
https://www.regular-expressions.info/brackets.html
Basicly the regex engine can find a list of strings matching the whole search pattern, and return you the parts inside the ().

Related

Remove everything after regex pattern match but keep pattern [duplicate]

This question already has answers here:
Using regex to remove all text after the last number in a string
(2 answers)
Closed 4 years ago.
I was searching for a way to remove all characters past a certain pattern match. I know that there are many similar questions here on SO but i was unable to find one that works for me. Basically i have a fixed pattern (\w\w\d\d\d\d), and i want to remove everything after that, but keep the pattern.
ive tried using:
test = 'PP1909dfgdfgd'
done = re.sub ('(\w\w\d\d\d\d/w*)', '\w\w\d\d\d\d/', test)
but still get the same string ..
example:
dirty = 'AA1001dirtydata'
dirty2 = 'AA1001222%^&*'
Desired output:
clean = 'AA1001'
You can use re.match() instead of re.sub():
re.match('\w\w\d\d\d\d', dirty).group(0) # returns 'AA1001'
Note: match will look for the regular expression at the beginning of the string you provide and only "match" the characters corresponding to the pattern. If you want to find the pattern partway through the string you can use re.search().

understanding this python regular expression re.compile(r'[ :]') [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 8 years ago.
Hi I am trying to understand python code which has this regular expression re.compile(r'[ :]'). I tried quite a few strings and couldnt find one. Can someone please give example where a text matches this pattern.
The expression simply matches a single space or a single : (or rather, a string containing either). That’s it. […] is a character class.
The [] matches any of the characters in the brackets. So [ :] will match one character that is either a space or a colon.
So these strings would have a match:
"Hello World"
"Field 1:"
etc...
These would not
"This_string_has_no_spaces_or_colons"
"100100101"
Edit:
For more info on regular expressions: https://docs.python.org/2/library/re.html

Explain the regular expression [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 8 years ago.
What does this regex mean? I know the functionality of re.sub but unable to figure out the 2nd part:
s = re.sub(r'\.([a-zA-Z])', r'. \1', s)
^^^^^^^
Can someone explain me the underlined part?
Next time it you should mention which programming language you are using, because regular expression syntaxes are very different from one language to another. Also when using regular expressions to replace something, then usually the second argument isn't a regular expression, but just a string with a special syntax, so knowing the programming language would help with that, too.
\1 is a back reference to what the first capturing group (expression in parentheses) matched.
So \.([a-zA-Z]) matches a period followed by a letter, and that letter is captured (stored/saved/remembered) because it surrounded by parentheses and use at the place of \1. The period and the letter is then replaced with a period, a space and that letter.
Examples:
.H becomes . H.
This.is.a.Test becomes This. is. a. Test

python re ?: example [duplicate]

This question already has answers here:
What is a non-capturing group in regular expressions?
(18 answers)
Reference - What does this regex mean?
(1 answer)
Closed 8 years ago.
i saw a regular expression (?= (?:\d{5}|[A-Z]{2})) in a python re example, and was very confused about the meaning of the ?: .
I also see the python doc, there is the explain:
(?:...)
A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.
who can give me an example, and explain why it works, thanks!!
Ordinarily, parentheses create a "capturing" group inside your regex:
regex = re.compile("(set|let) var = (\\w+|\\d+)")
print regex.match("set var = 12").groups()
results
('set', '12')
Later you can retrieve those groups by calling .groups() method on the result of a match. As you see whatever is inside parentheses is captured in "groups." But you might not care about all those groups. Say you only want to find what's in the second group and not the first. You need the first set of parentheses in order to group "get" and "set" but you can turn off capturing by putting "?:" at the beginning:
regex = re.compile("(?:set|let) var = (\\w+|\\d+)")
print regex.match("set var = 12").groups()
results:
('12',)
If you do not need the group to capture its match, you can optimize
this regular expression into Set(?:Value)?. The question mark and the
colon after the opening parenthesis are the syntax that creates a
non-capturing group. The question mark after the opening bracket is
unrelated to the question mark at the end of the regex. The final
question mark is the quantifier that makes the previous token
optional. This quantifier cannot appear after an opening parenthesis,
because there is nothing to be made optional at the start of a group.
Therefore, there is no ambiguity between the question mark as an
operator to make a token optional and the question mark as part of the
syntax for non-capturing groups, even though this may be confusing at
first. There are other kinds of groups that use the (? syntax in
combination with other characters than the colon that are explained
later in this tutorial.
color=(?:red|green|blue) is another regex with a non-capturing group.
This regex has no quantifiers.
From : http://www.regular-expressions.info/brackets.html
Also read: What is a non-capturing group? What does a question mark followed by a colon (?:) mean?

matching parentheses in python regular expression [duplicate]

This question already has answers here:
What is the difference between re.search and re.match?
(9 answers)
Closed 1 year ago.
I have something like
store(s)
ending line like "1 store(s)".
I want to match it using Python regular expression.
I tried something like re.match('store\(s\)$', text)
but it's not working.
This is the code I tried:
import re
s = '1 store(s)'
if re.match('store\(s\)$', s):
print('match')
In more or less direct reply to your comment
Try this
import re
s = '1 stores(s)'
if re.match('store\(s\)$',s):
print('match')
The solution is to use re.search instead of re.match as the latter tries to match the whole string with the regexp while the former just tries to find a substring inside of the string that does match the expression.
Python offers two different primitive
operations based on regular
expressions: match checks for a match
only at the beginning of the string,
while search checks for a match
anywhere in the string (this is what
Perl does by default)
Straight from the docs, but it does come up alot.
have you considered re.match('(.*)store\(s\)$',text) ?

Categories

Resources