简体   繁体   English

同一个正则表达式在一个脚本中起作用,而在另一个脚本中不起作用

[英]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. 我有一个简单的正则表达式( '(\\b) +-{1,} +(\\b)' ),它包含在脚本中( txt2tex.py ;行号17和48是重要的),可以将其指定为命令行中的另一个脚本( multilineRegex.py ;只需将一个正则表达式作为第一个参数,替换文本作为第二个参数,并将文件名作为第三个参数进行匹配)就可以了。

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: 在txt2tex.py中求值时,正则表达式与给定的输入文本不匹配,但是当我将其复制并粘贴到命令行并按以下方式调用multilineRegex.py时,它会按预期工作:

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 的Python:2.7.5
  • OS: OS X 10.9.5 作业系统:OS X 10.9.5

That's because your shell interprets the \\b s as control characters (backspace). 这是因为您的shell将\\b解释为控制字符(退格键)。 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 正常工作的同一个正则表达式模式无法在类中实现 - The same regex pattern that works fine doesn't work implemented into a Class 相同的 Python 命令可在一台计算机上运行,​​但在 Maya 中的另一台计算机上不起作用 - Same Python command works on one computer but doesn't on another in Maya 相同的 python 脚本在一台计算机上工作,但在另一台计算机上不起作用 - Same python script works in one computer but not in another PuLP 不适用于一个列表,但适用于另一个列表。 这两者有什么区别? - PuLP doesn't work with one list but works with another. What is the difference between these two? Python:REGEX在一个地方工作,但不能在另一个地方工作 - Python: REGEX works in one place, but not another with same input 具有open('filename')的Python脚本可用于IDLE,但不能在控制台中使用 - Python script with open('filename') works with IDLE but doesn't work in console Python 3 cgi脚本不起作用,但是python 2有效 - Python 3 cgi script doesn't work, but python 2 works SMTP电子邮件脚本不适用于Mac,但适用于Windows - SMTP Email script doesn't work on Mac but works on Windows `import pyspark`可在Jupyter中使用,但不适用于python shell / script - `import pyspark` works in Jupyter, but doesn't work with python shell/script Boolean 索引器脚本可以正常工作但无法正常工作 - Boolean indexer script works without Error but doesn't work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM