Reputation: 117
I have few patterns like:
orange.*
*.key.*
jug.*.key
Here, by *
- I mean exactly one word.
So, the pattern *.key.*
should match the string bar.key.door
(one word on each side) but not fruit.bar.key.door
(two words before key
).
How do i write a regex pattern for this in Python?
Upvotes: 0
Views: 1170
Reputation: 163497
One way you could match that pattern is to use anchors to assert the start ^
and the end $
of the line and match match the unknown part by using ^[^.]+
(a negated character class) or use \w+
to match one or more word characters.
For example:
import re
p = re.compile('^[^.]+\.key\.[^.]+$')
m = p.match('bar.key.door')
print (m.group())
Some options for your other patterns could be: ^orange\.\w+$
and ^jug\.[^.]+\.key$
Upvotes: 1
Reputation: 3894
There are various ways to implement it:
Option 1: ^[\w]+\.key\.[\w]+$
Option 2: ^[[:word:]]+\.key\.[[:word:]]+$
Option 3: ^[^.]+\.key\.[^.]+$
Option 4: ^[A-Za-z]+\.key\.[A-Za-z]+$
Hope it helps.
Upvotes: 0
Reputation: 28313
.
matches any character except a newline. to match the literal .
it needs to be escaped, like \.
.
*
- means exactly 1 word
*
is another regex character meaning match 0 or more repetitions of the previous character group. \w+
would match a word. a single word would imply the string terminates (before or after), so it can be checked for using ^
or $
.
check out the official re library documentation for more info. It has worked examples and is a very good tutorial for learning regex.
so, the 3 regex patterns would be:
p1 = r'orange\.\w+$'
p2 = r'^\w+\.key\.\w+$'
p3 = r'^jug\.\w+\.key$'
Upvotes: 0