【问题标题】:How to replace non-character surrounded string in python如何在python中替换非字符包围的字符串
【发布时间】:2015-10-08 08:34:02
【问题描述】:

我有一个带有参数集合的变量 (newArgs),我想替换此变量中出现的某个字符串。我可以使用 re.search 命令进入我的 if 条件:

if (re.search(item, newArgs)):

如果条件在 newArgs 中找到确切的项目,'if' 条件将不会做任何事情

当它进入'else'条件时,应该触发re.sub命令:

不工作:

newArgs = re.sub(argVariable+'=r(\S*\S)?', item, newArgs)

注意:我可以得到在此示例中值为“-Dweblogic.Stderr”的“argVariable”

如何用 'newArgs' 中的新 'item' 替换匹配的字符串?

要替换的示例字符串:

-Dweblogic.Stderr=/tmp/error.out

我想搜索 = 符号之外的任何内容,它会停止,直到它看到一个空格(因为超出空格是下一个参数)或者它是 newArgs 变量的结尾

我希望它被替换为:

-Dweblogic.Stderr=/apps/some/other/location/error.out

【问题讨论】:

    标签: python regex string


    【解决方案1】:
    newArgs = re.sub(argVariable+r'=\S*', item, newArgs)
    

    您需要将r 去掉引号并使用此正则表达式。

    【讨论】:

    • 像魅力一样工作!谢谢!当前参数:-Xverbosetimestamp -Dweblogic.Stderr=/tmp/error.out 新参数:-Xverbosetimestamp -Dweblogic.Stderr=/apps/some/other/location/error.out
    • @RustanRodriguez item 的内容是什么,如果解决了你的问题,也考虑接受
    猜你喜欢
    • 2017-04-13
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 2015-10-14
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多