1

I am trying to extract the name stored in the variable below. I am trying to extract using regular expression but I am getting a invalid syntax error.

import re
var = 'Thomas/Male/'
output = re.search('([\w.-]+)/([\w.-]+)', var)
if output:
    print output.group(1)

Expected output 1 : Thomas
Expected output 2 : Male

Could anyone help on this. Thanks

2
  • You confused what is what in the code. rextester.com/RFUU47934 Commented May 11, 2018 at 13:22
  • 3
    That's Python 2 code. You can't do print output.group(1) in Python 3. Also, you refer to a variable match without creating it first. Commented May 11, 2018 at 13:25

4 Answers 4

3

Check variables, and in python3 print() not print

import re
var = 'Thomas/Male/'
output = re.search('([\w.-]+)/([\w.-]+)', var)
if output:
    print(output.group(0))
    print(output.group(1))
    print(output.group(2))

Output:

Thomas/Male
Thomas
Male
Sign up to request clarification or add additional context in comments.

Comments

2

You can search for alphanumeric characters:

import re
var = 'Thomas/Male/'
name, gender = re.findall('\w+', var)

Output:

'Thomas'
'Male'

Comments

2

You can use str.split

var = 'Thomas/Male/'
var = var.split("/")
print(var[0], " = " ,var[1])

Output:

Thomas = Male

Comments

2

If the data is always in the form you posted (something/somethingElse/) you could probably accomplish this easier by using split() rather than regex:

var = 'Thomas/Male/'
var_split = var.split('/')
print(var_split[0])
print(var_split[1])

Output:

Thomas
Male

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.