使用 re.sub() 将模式大写并在该模式之前添加一些文本 [英] Using re.sub() to capitalize a pattern and add some text before that pattern

查看:26
本文介绍了使用 re.sub() 将模式大写并在该模式之前添加一些文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章是对我之前的问题的跟进.

所以我有以下字符串.

This post is a follow-up to my previous question.

So I have the following string.

string = "A / (1 + e ^ (-1 * X))"

我想创建一个函数来输出一个包含所有小写字母序列的字符串前一个用Math.

And I want to create a function to output a string that has all sequences of lowercase letters that is not followed by parenthesis in the previous string written in uppercase with a Math.

(1 + e) 将返回 (1 + Math.E)
(5 ^ 2 * pi) 将返回 (5 ^ 2 * Math.PI)

(1 + e) would return (1 + Math.E)
(5 ^ 2 * pi) would return (5 ^ 2 * Math.PI)

re.sub(r'([a-z]+)(?!\(.*?\))(?![a-z])', r'Math.\1', func)

正则表达式工作正常,但我不知道如何将模式大写.

The Regex is working fine, but I don't know how to uppercase the pattern.

推荐答案

只需使用一个函数,即

re.sub(r'([a-z]+)(?!\(.*?\))(?![a-z])', lambda x: f'Math.{x[1].upper()}', s)

这篇关于使用 re.sub() 将模式大写并在该模式之前添加一些文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆