我想使用re.MULTILINE
但是不 re.DOTALL
,这样我就可以拥有一个包含"任何字符"的正则表达式。通配符和与换行符不匹配的普通my dog smells
my cat bites
my fish
a b c
d e f
g h
通配符。
有办法做到这一点吗?我应该使用什么来匹配那些我想要包含换行符的实例中的任何字符?
答案 0 :(得分:46)
要匹配换行符或没有re.S
/ re.DOTALL
的“任何符号”,您可以使用以下任何一项:
[\s\S]
[\w\W]
[\d\D]
主要思想是字符类中相反的速记类与输入字符串中的任何符号匹配。
将其与(.|\s)
和其他变量进行比较,字符类解决方案效率更高,因为它涉及的回溯要少得多(与*
或+
量词一起使用时)。比较一个小例子:完成需要(?:.|\n)+
个45步,而[\s\S]+
只需要两步。
答案 1 :(得分:1)
[^]
在正则表达式中,方括号包含一个匹配字符的可能值的列表和/或范围。如果该列表为空,则表示[]
,字符串的任何字符都不能与之匹配。
现在,该列表和/或范围前面的插入符号,取消这些允许值。因此,在一个空列表的前面,任何字符(包括换行符)都将与之匹配。
所有功劳归于RegEx101.com。发生的事情是,当我试图在其主表达式栏中键入类似[^>]+
的内容时,我不小心遇到了这个棘手的代码。然后,将其悬停在我的脸上,出现一个“ 匹配任何字符,包括换行符”!
答案 2 :(得分:0)
正则表达式:(请注意也使用空格'')
class MobilesPipeline:
def open_spider(self, spider):
hostname = 'localhost'
username = 'postgres'
password = 'postgres' # your password
database = 'postgres'
self.connection = psycopg2.connect(host=hostname, user=username, password=password, dbname=database)
self.cur = self.connection.cursor()
def close_spider(self, spider):
self.cur.close()
self.connection.close()
def process_item(self, item, spider):
self.cur.execute("insert into mobiles(name,image) values(%s,%s)", (item['name'], item['image']))
self.connection.commit()
return item
[\S\n\t\v ]
“匹配项[0]”将包含:
“一只快速的棕色狐狸。 \ n 它跳过了懒狗”
import re
text = 'abc def ###A quick brown fox.\nIt jumps over the lazy dog### ghi jkl'
# We want to extract "A quick brown fox.\nIt jumps over the lazy dog"
matches = re.findall('###[\S\n ]+###', text)
print(matches[0])
匹配非空格字符的任何字符。
(请参阅:https://docs.python.org/3/library/re.html#regular-expression-syntax)