0

I'm trying to implement regular expressions in python so that I will only print part of a string and not a whole string. I'm trying to print the characters that are numbers and also precede the letter characters of this string. I'm getting an error with the beginning of string character here

Heres my code import re

var = "20cw"
var2 = re.compile(^[0-9]?[0-9], var)
print var2

Here is the error I'm getting

  File "./temp.py", line 5
    var2 = re.compile(^[0-9]?[0-9], var)
                      ^
SyntaxError: invalid syntax

Expected output is

20
2
  • Is there anything wrong with if var[:2].isdigit(): print var[:2]. Why leap at re for this? Commented Jun 9, 2017 at 7:06
  • @RolfofSaxony Sorry, I didn't give enough examples. The number in front is 2 digits in this example, but in my program it can 1 or 2 digits Commented Jun 10, 2017 at 2:28

1 Answer 1

1

Enclose the regex as string (with quotation marks):

var2 = re.findall('^\d{2}', var)
Sign up to request clarification or add additional context in comments.

5 Comments

Even better, use raw string (r'^\d{2}') to avoid accidental interpretation of backslash character
@Błotosmętek sometimes useful, but irrelevant for this case
The regex you suggest is different from the original one. It must be ^[0-9]{1,2} and if used with re.match, no ^ is necessary.
The regex is correct, from the description the OP wants to match on exactly two digits. It is OP's regex that is wrong.
@WiktorStribiżew the regex OP used is not matching his requirements, I'm trying to print the first two characters of this string IF the first two characters are numbers

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.