簡體   English   中英

正則表達式從字符串python中提取三個字符

[英]Regex to extract three characters from string python

我有一個字符串,例如testing_7_3_4_testing

我想將testing_7_3_4_testing替換為testing_7.3.4_testing ,我嘗試使用str.replace(/\\d_\\d/, ".")並得到一些非常奇怪的結果。 正則表達式專家請幫忙!

嘗試這個:

import re

my_strs = [
    'testing_7_3_4_testing',
    'testing_7_3_testing',
    'testing_7_3_4_5',
    'testing_71_312_4123_testing',
]

pattern = r"""
    (\d+)      #Match a digit, one or more times, captured in group 1, followed by...
    _          #an underscore, followed by...
    (?=\d+)    #a digit, one or more times, but do not include as part of the match
"""

for my_str in my_strs:
    new_str = re.sub(pattern, r'\1.', my_str, flags=re.X)
    print(new_str)

--output:--
testing_7.3.4_testing
testing_7.3_testing
testing_7.3.4.5
testing_71.312.4123_testing

模式(?=\\d+)表示要匹配一次或多次,但實際上不包括匹配數字作為匹配的一部分。

將每個數字保存到自己的保存組中 ,在替換字符串中引用這些組:

>>> import re
>>> s = "testing_7_3_4_testing"
>>> re.sub(r"(\d)_(\d)_(\d)", r"\1.\2.\3", s)
'testing_7.3.4_testing'

或者,我們可以使用替換函數 ,與第一種方法相比,該函數還處理輸入字符串中可變數目的數字:

>>> def replacement(m):
...     x, y, z = m.groups()
...     return x + y.replace("_", ".") + z
... 
>>> re.sub(r"(.*?_)([0-9_]+)(_.*?)", replacement, s)
'testing_7.3.4_testing'

非正則表達式方法將涉及通過_ ,切片和連接進行拆分:

>>> l = s.split("_")
>>> l[0] + "_" + ".".join(l[1:-1]) + "_" + l[-1]
'testing_7.3.4_testing'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM