簡體   English   中英

使用正則表達式查找格式為“ [number]”的字符串

[英]find string with format '[number]' using regex

我在django / python應用程序中有一個字符串,需要在[x]每個實例中搜索它。 這包括方括號和x,其中x是1到幾百萬之間的任何數字。 然后,我需要用自己的字符串替換x。

也就是說, 'Some string [3423] of words and numbers like 9898'將變成'Some string [mycustomtext] of words and numbers like 9898'

請注意,僅括號中的數字受影響。 我對regex不熟悉,但是認為這對我有用嗎?

正則表達式正是您想要的。 它是Python中的re模塊,您將要使用re.sub,它將類似於:

newstring = re.sub(r'\[\d+\]', replacement, yourstring)

如果您需要做很多事情,請考慮編譯正則表達式:

myre = re.compile(r'\[\d+\]')
newstring = myre.sub(replacement, yourstring)

編輯: 要重新使用數字 ,請使用正則表達式組:

newstring = re.sub(r'\[(\d+)\]',r'[mytext, \1]', yourstring)

仍然可以進行編譯。

使用re.sub

import re
input = 'Some string [3423] of words and numbers like 9898'
output = re.sub(r'\[[0-9]+]', '[mycustomtext]', input)
# output is now 'Some string [mycustomtext] of words and numbers like 9898'

由於這里沒有其他人跳進來,因此我將為您提供非Python版本的regex

\[(\d{1,8})\]

現在,在替換零件中,您可以使用“被動組” $ n進行替換(其中n =括號中對應於零件的數字)。 這一個是$ 1

暫無
暫無

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

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