Was wondering what the best way is to match \"test.this\"
from \"blah blah blah test.this@gmail.com blah blah\"
is? Using Python.
I\'ve tri
to escape non-alphanumeric characters of string variables, including dots, you could use re.escape
:
import re
expression = 'whatever.v1.dfc'
escaped_expression = re.escape(expression)
print(escaped_expression)
output:
whatever\.v1\.dfc
you can use the escaped expression to find/match the string literally.
"In the default mode, Dot (.) matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline." (python Doc)
So, if you want to evaluate dot literaly, I think you should put it in square brackets:
>>> p = re.compile(r'\b(\w+[.]\w+)')
>>> resp = p.search("blah blah blah test.this@gmail.com blah blah")
>>> resp.group()
'test.this'
A .
in regex is a metacharacter, it is used to match any character. To match a literal dot, you need to escape it, so \.
In your regex you need to escape the dot "\."
or use it inside a character class "[.]"
, as it is a meta-character in regex, which matches any character.
Also, you need \w+
instead of \w
to match one or more word characters.
Now, if you want the test.this
content, then split
is not what you need. split
will split your string around the test.this
. For example:
>>> re.split(r"\b\w+\.\w+@", s)
['blah blah blah ', 'gmail.com blah blah']
You can use re.findall:
>>> re.findall(r'\w+[.]\w+(?=@)', s) # look ahead
['test.this']
>>> re.findall(r'(\w+[.]\w+)@', s) # capture group
['test.this']
In javascript you have to use \. to match a dot.
Example
"blah.tests.zibri.org".match('test\\..*')
null
and
"blah.test.zibri.org".match('test\\..*')
["test.zibri.org", index: 5, input: "blah.test.zibri.org", groups: undefined]
This expression,
(?<=\s|^)[^.\s]+\.[^.\s]+(?=@)
might also work OK for those specific types of input strings.
import re
expression = r'(?<=^|\s)[^.\s]+\.[^.\s]+(?=@)'
string = '''
blah blah blah test.this@gmail.com blah blah
blah blah blah test.this @gmail.com blah blah
blah blah blah test.this.this@gmail.com blah blah
'''
matches = re.findall(expression, string)
print(matches)
['test.this']
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.