简体   繁体   中英

Pattern matching and replacing based from regex

I am trying to parse through a string and modify values that match a particular pattern. I am basically trying to convert the following R code into Python.

sample_formatted <- stringr::str_replace(sample, 
                      '(\\b[a-zA-Z]+):([a-zA-Z]\\b)', '\\1\\2')

I am completely new to Python regex and a struggling to figure out where to start. Any help will be greatly appreciated!

I guess then you can simply do a re.sub in Python:

import re

regex = r"(\b[a-zA-Z]+):([a-zA-Z]\b)"

test_str = ("abc:x\n"
    "DEf:y\n"
    "ABC:z")

subst = "\\1\\2"

result = re.sub(regex, subst, test_str)

if result:
    print (result)

The expression is explained on the top right panel of this demo if you wish to explore/simplify/modify it.

RegEx Circuit

jex.im visualizes regular expressions:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM