简体   繁体   中英

Same regex works in one script, doesn't work in another

I have a simple regex ( '(\\b) +-{1,} +(\\b)' ) that is included in a script ( txt2tex.py ; line numbers 17 and 48 are the important ones) and can be given to another script ( multilineRegex.py ; simply takes a regex to match against as it's 1st argument, replacement text as 2nd argument, and file name as 3rd) from the command line.

The regex doesn't match a given input text when evaluated inside txt2tex.py, but when I copy and paste it to the command line and invoke multilineRegex.py as follows, it works as expected:

multilineRegex.py '(\b) +-{1,} +(\b)' '---' input.txt

I noticed this discrepancy as I was playing around with regexes. Any ideas as to what I am doing wrong?

Used the following line to verify this behaviour:

Here's something - arbit for you to think of.

Details:

  • Python: 2.7.5
  • OS: OS X 10.9.5

That's because your shell interprets the \\b s as control characters (backspace). You can demonstrate that by executing:

$ echo 'hello\bworld'
hellworld

When giving the regex to your script, escape it with an additional backslash:

multilineRegex.py '(\\b) +-{1,} +(\\b)' '---' input.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM