151

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 tried re.split(r"\b\w.\w@")

Georgy
  • 12,464
  • 7
  • 65
  • 73
  • `\w` only matches a single character - you probably want `\w+` – Peter Boughton Dec 21 '12 at 11:53
  • 3
    Here's [an email validation regex](http://ex-parrot.com/~pdw/Mail-RFC822-Address.html) if you are looking for one. – chucksmash Dec 21 '12 at 12:02
  • See also: [How to fix “ DeprecationWarning: invalid escape sequence” in Python?](https://stackoverflow.com/questions/52335970/how-to-fix-string-deprecationwarning-invalid-escape-sequence-in-python) – Gabriel Staples Mar 17 '21 at 03:50

7 Answers7

241

A . in regex is a metacharacter, it is used to match any character. To match a literal dot in a raw Python string (r"" or r''), you need to escape it, so r"\."

Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265
Yuushi
  • 25,132
  • 7
  • 63
  • 81
  • 10
    Unless the regular expression is stored inside a regular python string, in which case you need to use a double `\ ` (`\\ `) instead. So, all of these are equivalent: `'\\.'`, `"\\."`, `r'\.'`, `r"\."`. See: https://stackoverflow.com/a/52335971/4561887. – Gabriel Staples Mar 17 '21 at 03:54
  • I went ahead and added an answer: https://stackoverflow.com/a/66666859/4561887. – Gabriel Staples Mar 17 '21 at 04:12
  • @GabrielStaples Minor nitpick--the `r"..."` syntax is Python "raw" strings, not "regular" strings. – GrandOpener May 27 '21 at 16:59
  • 1
    @GrandOpener, correct, as I explain [in my answer](https://stackoverflow.com/a/66666859/4561887) (please take a look at it). Please re-read my comment above too. I stated that regular strings require the double-slash: `'\\.'`, `"\\."`, while raw strings require the single slash: `r'\.'`, `r"\."`, which was the entire point of my comment. This answer doesn't make that clear. I wanted to make that clear in my comment for anyone stumbling upon this answer who's using regular strings, as this answer is intended for raw strings only. – Gabriel Staples May 27 '21 at 17:58
  • 1
    @GrandOpener, I've updated Yuushi's answer to make it clear his or her answer applies to raw strings only. Yuushi is welcome to edit his answer and [link to my answer](https://stackoverflow.com/a/66666859/4561887) if he wants in order to show how two backslashes are needed for regular strings. (I'm trying to keep my edits to his answer to a minimum.) – Gabriel Staples May 27 '21 at 18:01
  • @GabrielStaples Ah I see now what you were saying. I didn't parse the "unless...in which case" correctly on first reading of your comment. Never mind then! – GrandOpener May 27 '21 at 18:11
59

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']
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • 2
    +1 for character class. Using gcovr from a Jenkinsfile and trying to exclude dot directories, and Jenkins doesn't understand escape sequences. The character class worked beautifully. – Jonathan E. Landrum Jun 01 '18 at 20:09
15

"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'
StackUser
  • 587
  • 6
  • 26
3

Here is my add-on to the main answer by @Yuushi:

Summary

These are NOT allowed.

'\.'   # NOT a valid escape sequence in **regular** Python single-quoted strings
"\."   # NOT a valid escape sequence in **regular** Python double-quoted strings

They'll cause a warning like this:

DeprecationWarning: invalid escape sequence \.

All of these, however, ARE allowed and are equivalent:

# Use a DOUBLE BACK-SLASH in Python _regular_ strings
'\\.'  # **regular** Python single-quoted string
"\\."  # **regular** Python double-quoted string

# Use a SINGLE BACK-SLASH in Python _raw_ strings 
r'\.'  # Python single-quoted **raw** string
r"\."  # Python double-quoted **raw** string

Explanation

Keep in mind, the backslash (\) char itself must be escaped in Python if used inside of a regular string ('some string' or "some string") instead of a raw string (r'some string' or r"some string"). So, keep in mind the type of string you are using. To escape the dot or period (.) inside a regular expression in a regular python string, therefore, you must also escape the backslash by using a double backslash (\\), making the total escape sequence for the . in the regular expression this: \\., as shown in the examples above.

References

  1. MAIN AND OFFICIAL REFERENCE: https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals enter image description here
  2. [answer by @Sean Hammond] How to fix "<string> DeprecationWarning: invalid escape sequence" in Python?

    If you want to put a literal \ in a string you have to use \\

Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265
1

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.

Ali Abul Hawa
  • 552
  • 6
  • 13
-3

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]
Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265
Zibri
  • 9,096
  • 3
  • 52
  • 44
-3

This expression,

(?<=\s|^)[^.\s]+\.[^.\s]+(?=@)

might also work OK for those specific types of input strings.

Demo

Test

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)

Output

['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.


Emma
  • 27,428
  • 11
  • 44
  • 69