1

New to python regex and would like to write something that matches this

<name>.name.<age>.age@<place>

I can do this but would like the pattern to have and check name and age.

pat = re.compile("""
       ^(?P<name>.*)
        \.
        (?P<name>.*)
        \.
        (?P<age>.*)
        \.
        (?P<age>.*?)
        \@
        (?P<place>.*?)
        $""", re.X)

I then match and extract the values. res = pat.match('alan.name.65.age@jamaica')

Would like to know the best practice to do this?

3
  • What's the point of repeating the (?P<name>.*) group? Commented Oct 28, 2019 at 13:17
  • I've edited it. The argument to match is my requirement. Its a pattern with name and age being always present, hence would like to check it. @Tomalak Commented Oct 28, 2019 at 13:22
  • Ahh, the substring '.name' is always present, I see. Commented Oct 28, 2019 at 13:24

3 Answers 3

3

Match .name and .age literally. You don't need new groups for that.

pat = re.compile("""
       ^(?P<name>[^.]*)\.name
        \.
        (?P<age>[^.]*)\.age
        \@
        (?P<place>.*)
        $""", re.X)

Notes

  • I've replaced .* ("anything") by [^.]* ("anything except a dot"), because the dot cannot really be part of the name in the pattern you show.
  • Think whether you mean * (0-unlimited occurrences) or rather + (1-unlimited occurrences).
Sign up to request clarification or add additional context in comments.

Comments

2

No reason not to allow . in names, e.g. John Q. Public.

import re

pat = re.compile(r"""(?P<name>.*?)\.name
                 \.(?P<age>\d+)\.age
                 @(?P<place>.*$)""",
                 flags=re.X)
m = pat.match('alan.name.65.age@jamaica')
print(m.group('name'))
print(m.group('age'))
print(m.group('place'))

Prints:

alan
65
jamaica

Comments

0

You dont need the groups if you use re.split :

re.split('\.name\.|\.age', "alan.name.65.age@jamaica")

This will return name and age as first two elements of the list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.