通过pyperclip多行复制文本搜索正则表达式问题

时间:2018-09-24 20:16:55

标签: python regex python-3.x newline pyperclip

如果搜索表达式涉及pyperclip.paste()换行符,则试图通过\n通过正则表达式进行搜索对我来说是一件罕见的事情。

对不起,我的英语。

搜索时,我通过赋给text变量的三重引号进行搜索:

import re

text = '''
This as the line 1
This as the line 2
'''

pattern = re.compile(r'\d\n\w+')
result = pattern.findall(text)
print(result)

它实际上打印换行符\n。 Wich是我想要的,或者几乎是我想要的。

  

»»»['1 \ nThis']

但是当要搜索的字符串来自剪贴板中复制的文本时,问题就开始了。

This as the line 1
This as the line 2

说我只选择文本并将其复制到剪贴板,我希望正则表达式从中提取相同的先前输出。 这次我需要使用pyperclip模块。

因此,忘记前面的代码,而是写成这样:

import re, pyperclip

text = pyperclip.paste()

pattern = re.compile(r'\d\n\w+')
result = pattern.findall(text)
print(result)

这是结果:

  

»»»[]

只有两个括号。我(出于经验不足)发现导致此问题的原因是\n字符。它与python之间的冲突(也为\ n字符)无关,因为我们避免使用'r'。

我已经找到了一个不太清楚的解决方案(对我来说,几乎是因为我现在只了解python的基本知识)。

import re, pyperclip

text = pyperclip.paste()
lines = text.split('\n')
spam = ''

for i in lines:
    spam = spam + i

pattern = re.compile(r'\d\r\w+')
result = pattern.findall(spam)
print(result)

请注意,我选择了\n\r会导致同样的不良行为打印,而不是\n来检测上一个正则表达式中的换行。仅括号)。 \r\s可以互换,输出有效,但是:

  

»»»['1 \ rThis']

使用\r代替\n

至少对我来说是个小胜利。

如果您可以向我解释一个更好的解决方案,这对我有很大帮助,几乎可以理解为什么会这样。您也可以推荐一些概念进行研究,以全面理解这一点。

1 个答案:

答案 0 :(得分:0)

粘贴时获得\r的原因是因为您是从Windows计算机粘贴的。在Windows上,换行符由\r\n表示。请注意,\s\r不同。 \s表示任何空白字符。 \r只是回车符。

文本:

This as the line 1 This as the line 2

实际上看起来像:

This as the line 1\r\n This as the line 2\r\n

在Windows计算机上。

在正则表达式中,\d\r匹配到第一行的结尾:1\r,但是\w+不匹配\n。您需要将第一个正则表达式编辑为:

pattern = re.compile(r'\d\r\n\w+')

来源:Do line endings differ between Windows and Linux?