-1

I used regex101 to test a simple regex (\D+\n*), but the code generated gives a syntax error.

import re
p = re.compile(ur"\D+\n*", re.UNICODE)
test_str = u"2080 usec, 240 usec\n1780 usec, 260 usec\n700 usec, 240 usec\n700 usec, 240 usec\n2480 usec, 240 usec\n700 usec, 240 usec\n700 usec, 240 usec\n"
subst = u""

result = re.sub(p, subst, test_str)

What's wrong? Using python 3.4.3.

2
  • Can you provide the syntax error? Jul 27, 2015 at 14:05
  • It highlights the second " in "\D+\n*"
    – byrass
    Jul 27, 2015 at 14:07

3 Answers 3

3

The ur prefix is not supported in Python 3. Use r instead.

Python 2.7:

>>> ur"\D+\n*"
u'\\D+\\n*'

Python 3:

>>> ur"foo"
  File "<ipython-input-12-e07f08d3b66c>", line 1
    ur"foo"
          ^
SyntaxError: invalid syntax

This is one of the least helpful Python errors I've seen, to be honest.

0
1

Use only r string prefix instead of ur.

3
  • Works great, why is this an issue?
    – byrass
    Jul 27, 2015 at 14:11
  • The combined prefix is not supported in the recent versions of Python3.
    – dlask
    Jul 27, 2015 at 14:12
  • doesn't really explain why the error was shown at the end of the literal though
    – MightyPork
    Jul 27, 2015 at 14:49
0

If you import re, and use re.compile(r'\D+\n*'), it seems to work.

What exactly was wrong though I do not know.

1
  • I do import, forgot to copy. THX
    – byrass
    Jul 27, 2015 at 14:06

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.