【问题标题】:How to combine/join regular string with regex result?如何将常规字符串与正则表达式结果结合/加入?
【发布时间】:2014-06-19 13:21:40
【问题描述】:

所以我有这个简单的代码:

def modify_mysql_log():
    #/var/log/mysql/mysql.log
    #Change: queries
    f=open("../mysql/mysql.log")
    t=open("../mysql/mysql2.log","w")
    for line in f:
        line=re.sub(r'Query\s*SELECT[A-Za-z\s+\W_]*\'',random.choice(queries),line)
        t.write(line)
    f.close()
    t.close()

现在我想做的是,我希望能够用我用正则表达式找到的查询替换我曾经搜索过的正则表达式,并结合 random.choice(queries) 和正则表达式结果。我查看了其他 re 函数,但不知何故我不知道该怎么做。

【问题讨论】:

  • 你试过像"%s" % ("text")"{}".format("text")这样的字符串格式化函数吗?

标签: python regex string substitution


【解决方案1】:
line=re.sub(r'REGEX', random.choice(queries), line)

此代码将返回通过用 random.choice(queries) 替换正则表达式的“最左边的非重叠出现”获得的字符串。如果未找到正则表达式,则返回行。

如果我正确理解了问题,我会尝试在该行中搜索正则表达式并使用 string.replace(string_found_by_regex, random.choice(queries) + line)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 2012-11-29
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多