我在堆栈溢出中发现了一些类似的主题,但我是Python和Reg的新手。
我有一根绳子
“2009年,柏林梅斯高级酒店全面翻新,拥有168间空调客房,紧邻柏林国际商会和展览中心。所有客房都配有will,大堂内的两台iPoint电脑都可以免费上网。我们提供24小时的酒吧、小吃和接待服务。从早上4点到下午12点,在8楼享用我们的早餐自助餐,您可以看到整个柏林的美景。您可以看到酒店旁边的免费停车场。”
模式应该是:comma, double quote|any text with commas |double quote, comma。我需要在双引号中替换逗号,例如用@字符。我应该使用哪种reg exp模式?
我试过这个:
r',"([.*]*,[.*]*)*",' 有不同的变化,但不起作用。
谢谢你的回答,问题解决了。
发布于 2013-08-14 15:32:30
如果您需要做的就是用@字符替换逗号,那么您应该考虑执行一个str_replace,而不是regex。
str_a = "Completely renovated in 2009, the 2-star Superior Hotel Ibis Berlin Messe, with its 168 air-conditioned rooms, is located right next to Berlin's ICC and exhibition center. All rooms have Wi-Fi, and you can surf the Internet free of charge at two iPoint-PCs in the lobby. We provide a 24-hour bar, snacks and reception service. Enjoy our breakfast buffet from 4am to 12pm on the 8th floor, where you have a fantastic view across Berlin. You will find free car parking directly next to the hotel."
str_a = str_a.replace('","', '@') #commas inside double quotes
str_a = str_a.replace(',', '@') #replace just commas
print str_a编辑:或者,您可以列出要替换的内容,然后循环执行替换。例如:
to_replace = ['""', ',', '"']
str_a = "Completely renovated in 2009, the 2-star Superior Hotel Ibis Berlin Messe, with its 168 air-conditioned rooms, is located right next to Berlin's ICC and exhibition center. All rooms have Wi-Fi, and you can surf the Internet free of charge at two iPoint-PCs in the lobby. We provide a 24-hour bar, snacks and reception service. Enjoy our breakfast buffet from 4am to 12pm on the 8th floor, where you have a fantastic view across Berlin. You will find free car parking directly next to the hotel."
for a in to_replace:
str_a = str_a.replace(a, '@')
print str_a发布于 2013-08-14 15:41:21
嗯,你的审判官很可疑。
,"([.*]*,[.*]*)*",[.*]将匹配文字点或星号(.和*在字符类中成为文字)。
此外,如果这实际上可以匹配字符串中的某些内容,则只能替换一个逗号,因为其余的字符串(包括逗号)将由regex使用,一旦被使用,就不能再次替换,除非运行一个循环,直到没有更多逗号替换。
你可以用re.sub来替换那些逗号(你可以谷歌它,我相信有足够的文档)。如果只有一对双引号,则可以确保只替换逗号后面的一个双引号:
,(?=[^"]*"[^"]*$)[^"]指的是不是双引号的字符。[^"]*意味着这将重复0次或更多次。
$指的是行的结尾。
现在,展望(?= ... )确保逗号前面有什么内容。
请参见与这里匹配的逗号。
在此之后,您可以简单地将逗号替换为您想要的值。
str = re.sub(r',(?=[^"]*"[^"]*$)', '@', str)但是,如果有多个双引号,您应该确保前面有一个奇数的双引号。这可以通过使用regex来完成:
,(?=[^"]*"[^"]*(?:"[^"]*"[^"]*)*$)顺便说一句,(?: ... )是一个非捕获组。
发布于 2013-08-14 15:41:46
你可以试试这个(虽然相当致命)。这里的诀窍是,双引号中的任何字符,后面跟着奇数双引号,当然,假设双引号是平衡的:
s = 'some comma , outside "Some comma , inside" , "Completely , renovated in 2009",'
import re
s = re.sub(r',(?=[^"]*"(?:[^"]*"[^"]*")*[^"]*$)', "@", s)
print s输出
some comma , outside "Some comma @ inside" , "Completely @ renovated in 2009",https://stackoverflow.com/questions/18235923
复制相似问题