在python中使用正则表达式将两个字符替换为两个不同的字符

时间:2018-07-10 18:05:59

标签: regex python-3.x

我想在一个操作中使用regex在python中用两个其他不同字符替换两个不同字符。例如:单词是“ a / c stuff”,我想在一行regex.sub()行中使用regex将其转换为“ ac_stuff”。 我在这里搜索,但是找到了使用替换功能解决此问题的方法,但是我希望在一行中使用正则表达式来做到这一点。 谢谢您的帮助!

1 个答案:

答案 0 :(得分:2)

使用 buildscript { ext { springBootVersion = '2.0.2.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' apply plugin: 'war' group = 'br.com.mngs.pacs' sourceCompatibility = 1.8 repositories { mavenCentral() } configurations { providedRuntime } dependencies { providedCompile('org.springframework.boot:spring-boot-starter-web-services') providedRuntime('org.springframework.boot:spring-boot-starter-undertow') providedRuntime group:'javax.servlet', name: 'javax.servlet-api' testCompile('org.springframework.boot:spring-boot-starter-test') providedCompile project(":repositories") providedCompile project(":entities") providedCompile project(":connection") } configurations.all { exclude group: "org.springframework.boot", module: "spring-boot-starter-tomcat" }

可以在一行中做到这一点在技术上可行,但并不完美
<?xml version='1.0' encoding='UTF-8'?>
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.1">
    <deployment>
        <exclusions>
            <module name="com.fasterxml.jackson.core.jackson-annotations"/>
            <module name="com.fasterxml.jackson.core.jackson-core"/>
            <module name="com.fasterxml.jackson.core.jackson-databind"/>
            <module name="com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider"/>
            <module name="org.jboss.resteasy.resteasy-jackson2-provider"/>
        </exclusions>
    </deployment>
</jboss-deployment-structure>

使用re.sub更好(更快)的方式

re.sub("[/ ]", (lambda match: '' if match.group(0) == '/' else '_'), "a/c stuff")

str.translate

最可读的方法可能是通过"a/c stuff".translate(str.maketrans({'/': None, ' ': '_'})) ,尽管这种方法不能很好地适应许多替代品。

"a/c stuff".translate(str.maketrans(' ', '_', '/'))