python两个字符串替换_用regex,python替换两个字符串之间的字符串(Replacing a string between two strings on more then one occ...

用regex,python替换两个字符串之间的字符串(Replacing a string between two strings on more then one occasion with regex, python)

我正在尝试使用正则表达式来查找和替换文件中两个字符串之间的文本字符串。 我遇到的问题是我希望它在找到“结束”字符串后“中断”,而是替换第一个“开始”字符串和最后一个“结束”字符串之间的所有文本。

_copyright = 'BEGIN COPYRIGHT \n The replacing string \n END COPYRIGHT'

_file = re.sub(r'BEGIN COPYRIGHT[\w\s]*END COPYRIGHT',_copyright, _file)

开始版权

FOO

结束版权

开始版权

酒吧

结束版权

所以foo和bar都应该成为“替换字符串”,但文档变成了

开始版权

替换字符串

结束版权

I'm trying to use a regex to find and replace a text string between two strings in a file. The problem I am having is that I want it to "break" after finding "End" string, but instead it replaces all text between the first "begin" string and the last "End" string.

_copyright = 'BEGIN COPYRIGHT \n The replacing string \n END COPYRIGHT'

_file = re.sub(r'BEGIN COPYRIGHT[\w\s]*END COPYRIGHT',_copyright, _file)

BEGIN COPYRIGHT

FOO

END COPYRIGHT

BEGIN COPYRIGHT

BAR

END COPYRIGHT

So both foo and bar should become "The replacing string", but the document turns into

BEGIN COPYRIGHT

The replacing string

END COPYRIGHT

原文:https://stackoverflow.com/questions/12784624

2020-09-16 16:09

满意答案

至少,你需要使星形量词变得懒惰:

_file = re.sub(r'BEGIN COPYRIGHT[\w\s]*?END COPYRIGHT',_copyright, _file)

否则, [\w\s]*将贪婪地匹配尽可能多的字符,包括任何介入的END COPYRIGHT/BEGIN COPYRIGHT序列。

另一种稍微更明确的方法是:

_file = re.sub(r'''(?x)BEGIN COPYRIGHT

(?:(?!(?:END|BEGIN) COPYRIGHT)[\w\s])*

END COPYRIGHT''',_copyright, _file)

后一版本只有当它不在子串END COPYRIGHT或BEGIN COPYRIGHT的开头时匹配[\w\s] ,因此即使有人忘记将END COPYRIGHT部分放在那里也不会超出其界限。

At the very least, you need to make the star quantifier lazy:

_file = re.sub(r'BEGIN COPYRIGHT[\w\s]*?END COPYRIGHT',_copyright, _file)

Otherwise, [\w\s]* will greedily match as many characters as it can, including any intervening END COPYRIGHT/BEGIN COPYRIGHT sequences.

Another, slightly more explicit way would be to do this:

_file = re.sub(r'''(?x)BEGIN COPYRIGHT

(?:(?!(?:END|BEGIN) COPYRIGHT)[\w\s])*

END COPYRIGHT''',_copyright, _file)

The latter version matches [\w\s] only if it's not at the start of the substring END COPYRIGHT or BEGIN COPYRIGHT and therefore doesn't overstep its bounds even if someone forgot to put the END COPYRIGHT part there.

2012-10-08

相关问答

使用re.findall() : result = re.findall(r'var="(.*?)"', test)

print(result) # ['this', 'that']

Use re.findall(): result = re.findall(r'var="(.*?)"', test)

print(result) # ['this', 'that']

如果您正在寻找,请告诉我: import re

def smallest_between_two(a, b, text):

return min(re.findall(re.escape(a)+"(.*?)"+re.escape(b),text), key=len)

print(smallest_between_two(' ', '(', 'def test()'))

print(smallest_between_two('[', ']', '[this one][not this o...

要匹配说明一:和解释二之间的文本:您可以使用DOTALL标志在组中捕获它,或使用内联修饰符 (?s)使点匹配换行符。 Explanation One:\s*(.*?)\s*Explanation Two 说明 Explanation One:字面匹配 \s*匹配空白字符的零或倍 (.*?)在一个组中捕获零个或多个非贪婪的字符 \s*匹配空白字符的零或倍 Explanation Two匹配 正则表达式演示 演示Python To match the text between Explanation ...

这里有另一个解决方案(我还使用“非贪婪”修饰符,通过在后面放*来重写正则表达式,因为我发现它更具可读性)。 由r"\1"引用的组以parenthises作为未命名的组完成。 还使用re.compile作为样式首选项以减少参数的数量: line = "I go to Bridgebrook i go out some times on Tuesday night i go to Youth clob ...

用ast模块做这件事最好,就像jezrael做的那样。 这是另一个正则表达式的解决方案: import re

st = "'a': '1', 'b': '2.3', 'c': 'name', 'd': 229, 'e': '', 'f': '228', 'g': 12"

print re.findall(r'\'\S+?\':\s*\'?(.*?)\'?(?:,|$)', st)

输出: ['1', '2.3', 'name', '229', '', '228', '12']

在regex1...

尝试使用非贪婪量词: (?<=the)(.*?)(?=red dog)

这将更改表达式的行为,以便内部组仅匹配满足模式所需的少量字符。 但是,我应该指出,在这种情况下,使用lookarounds可能不是必需的。 你可以简单地使用这样的模式: .*the(.*?)red dog

并提取相关的捕获组。 第一个.*是贪婪的,这意味着模式将匹配它在满足模式的字符串中可以找到的最后一个。 这是C#中的一个工作示例: var input = "If the quick brown dog jumps ov...

在正则表达式中使用外观的组合。 reg = "(?<=%s).*?(?=%s)" % (str1,str2)

说明 : Lookarounds是零宽度断言。 它们不会消耗字符串上的任何字符。 (?<= # look behind to see if there is:

gh # 'gh'

) # end of look-behind

.*? # any character except \n (0 or more times)

(?= # look...

您可以使用否定字符类和参考捕获组#1作为匹配结果。 //([^/]+)/

说明: // # '//'

( # group and capture to \1:

[^/]+ # any character except: '/' (1 or more times)

) # end of \1

/ # '/'

You can use a negated character class and reference c...

为什么不首先捕获整个单词列表然后解析呢? objRegEx.Pattern = ":\s*([\S\s]*)\s?WORKSTATION#"

然后,你的oRegResults将包含1个字符串,其中包含你可以调用的所有单词(分隔符为换行符)以获取数组中的单词。 Why not capture the whole list of words first then parse it? objRegEx.Pattern = ":\s*([\S\s]*)\s?WORKSTATION#"

Then, yo...

至少,你需要使星形量词变得懒惰: _file = re.sub(r'BEGIN COPYRIGHT[\w\s]*?END COPYRIGHT',_copyright, _file)

否则, [\w\s]*将贪婪地匹配尽可能多的字符,包括任何介入的END COPYRIGHT/BEGIN COPYRIGHT序列。 另一种稍微更明确的方法是: _file = re.sub(r'''(?x)BEGIN COPYRIGHT

(?:(?!(?:END|BEGIN) CO...

相关文章

Python 字符串操作,字符串序列用于表示和存储文本,python中字符串是不可变的,一旦声明,不能

...

字符串的格式化 在python中也有类似于c中的printf()的格式输出标记。在python中格式化

...

命令格式: SET key value 把字符串值value存储到key中。如果存在此key,SE

...

【字符串与数组】 Q:Write a method to replace all spaces in

...

我想遍历一个字符串的每一个字符,以前是用string.toCharArray()来转换成一个char[

...

Java String类 字符串广泛应用在Java编程中,在Java中字符串属于对象,Java提

...

无论是对程序的本地化还是国际化,都会涉及到字符编码的转换的问题。尤其在web应用中常常需要处理中文字符

...

比如“12344321我爱java”与“1我432爱2134ajav”被认为两个字符串相等!

比如:String str="123456abcdef654321"; 我想以每

...

今天遇见一个问题.不知道怎么解决. 如: 自己建立了一个文件read.txt 里面存放这样的 键值

...

最新问答

如果启用了复制处理程序,请确保将其置于其中一个安全角色之后。 我见过人们做的另一件事是在不同的端口上运行admin。 最好在需要auth的页面上使用SSL,这样你就不会发送明确的密码,因此管理和复制将发生在8443上,而常规查询将在8080上发生。 如果您要签署自己的证书,请查看此有用的SO页面: 如何在特定连接上使用不同的证书? I didn't know that /admin was the context for SOLR admin because /admin does not re

第一:在您的样本中,您有: 但是你在询问 //td[@class=‘CarMiniProfile-TableHeader’] (注意TableHeader中的大写'T')。 xpath区分大小写。 第二:通过查询// td [@ class ='CarMiniProfile-TableHeader'] / td,你暗示你在外部td中有一个'td'元素,而它们是兄弟姐妹。 有很多方法可以在这里获得制作和模型

这是你的答案: http://jsfiddle.net/gPsdk/40/ .preloader-container { position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; background: #FFFFFF; z-index: 5; opacity: 1; -webkit-transition: all 500ms ease-out;

问题是,在启用Outlook库引用的情况下, olMailItem是一个保留常量,我认为当您将Dim olMailItem as Outlook.MailItem ,这不是问题,但是尝试设置变量会导致问题。 以下是完整的解释: 您已将olMailItem声明为对象变量。 在赋值语句的右侧,在将其值设置为对象的实例之前,您将引用此Object 。 这基本上是一个递归错误,因为你有对象试图自己分配自己。 还有另一个潜在的错误,如果之前已经分配了olMailItem ,这个语句会引发另一个错误(可能是

我建议使用wireshark http://www.wireshark.org/通过记录(“捕获”)设备可以看到的网络流量副本来“监听”网络上发生的对话。 当您开始捕获时,数据量似乎过大,但如果您能够发现任何看起来像您的SOAP消息的片段(应该很容易发现),那么您可以通过右键单击并选择来快速过滤到该对话'关注TCP Stream'。 然后,您可以在弹出窗口中查看您编写的SOAP服务与Silverlight客户端之间的整个对话。 如果一切正常,请关闭弹出窗口。 作为一个额外的好处,wireshar

Android默认情况下不提供TextView的合理结果。 您可以使用以下库并实现适当的aligntment。 https://github.com/navabi/JustifiedTextView Android Does not provide Justified aligntment of TextView By default. You can use following library and achieve proper aligntment. https://github.com/

你的代码适合我: class apples { public static void main(String args[]) { System.out.println("Hello World!"); } } 我将它下载到c:\ temp \ apples.java。 以下是我编译和运行的方式: C:\temp>javac -cp . apples.java C:\temp>dir apples Volume in drive C is HP_PAV

12个十六进制数字(带前导0x)表示48位。 那是256 TB的虚拟地址空间。 在AMD64上阅读wiki(我假设你在上面,对吗?)架构http://en.wikipedia.org/wiki/X86-64 12 hex digits (with leading 0x) mean 48 bits. That is 256 TB of virtual address space. Read wiki on AMD64 (I assume that you are on it, right?) ar

这将取决于你想要的。 对象有两种属性:类属性和实例属性。 类属性 类属性对于类的每个实例都是相同的对象。 class MyClass: class_attribute = [] 这里已经为类定义了MyClass.class_attribute ,您可以使用它。 如果您创建MyClass实例,则每个实例都可以访问相同的class_attribute 。 实例属性 instance属性仅在创建实例时可用,并且对于类的每个实例都是唯一的。 您只能在实例上使用它们。 在方法__init__中定

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值