簡體   English   中英

使用Python的re模塊查找匹配給定模式的字符串並分隔行

[英]Finding a string matching a given pattern and separating lines using Python's re module

在一個隨機字符串中,我需要找到一個匹配給定模式的字符串,然后放入; 在此字符串之后。 我認為我應該使用re來做到這一點,但是我並不那么熟悉。

輸入示例:

this is the first part of string 1/32 part this is the second part of string

其結果是,我需要把; 1/32 part ,例如

this is the first part of string 1/32 part; this is the second part of string

我知道我應該使用re ,而且我知道我應該將re.match與看起來像[1-1000]/[1-1000]\\spart re.match的模式一起使用,但是我不確定從這里開始。

編輯: 1/32是一個示例,它可以是65/123 1/3 65/123 1/3 65/123 1/3 6/7

您只需要使用re模塊中的re.matchre.sub以及以下正則表達式

import re

my_str = 'this is the first part of string 1/32 part this is the second part of string'
my_regex = r'(\d+/\d+\s+part)'

if re.match(my_regex, my_str):
    print(re.sub(my_regex, r'\1,', my_str))  # this will print: 1/32 part,
    # ...

如果您需要多行來匹配同一個正則表達式,就需要在正則表達式中添加一些額外的標志。 請參閱此處的此類標志列表。

你可以在這里看到正則表達式


快速替換(可能會有更好的方法)是在所需的匹配零件之前和之后也進行零件匹配,並執行以下操作:

import re

my_str = 'this is the first part of string 1/32 part this is the second part of string'
my_regex = r'(.*)(\s+\d+/\d+\s+part)(.*)'

condition = re.match(my_regex, my_str)

if condition:
    part = re.sub(my_regex, r'\2,', my_str)

x = condition.group(1) + part + condition.group(3)
print(x)

將輸出修改后的字符串:

這是字符串的第一部分1/32部分,這是字符串的第二部分

具有以上所有功能的簡單的單行函數將是:

import re


def modify_string(my_str, my_regex):
    return re.sub(my_regex, r'\1,', my_str)

if __name__ == '__main__':
    print(modify_string('first part of string 1/32 part second part of string', r'(\d+/\d+\s+part)'))

但是我建議保持這種狀況。 以防萬一

您的用例稱為替換。 這正是re.sub函數的用途。

import re

s = "bla 1/6 part bla bla 76/88 part 12345/12345 part bla"
print(s)
s = re.sub(r'(\b\d{1,4}/\d{1,4} part)', r'\1;', s)
print(s)

這個的輸出是

bla 1/6 part; bla bla 76/88 part; 12345/12345 part bla

注意遺失; 在最后出現的part

我使用{}量詞將分數的分子和分母限制為4個十進制數字,這是您用[1-1000]表示法提到的。 它甚至可以更好地近似為1?\\d{1,3} (但這也不完全相同,例如還允許使用1999/1999[1]


[1] ps正如三元論者所評論的 ,十進制數從1到1000的精確正則表達式是[1-9]([0-9][0-9]?)?|1000 ,看起來有點復雜,但是如果您將唯一的4位數字1000分開,並在1至3位數字部分上使用一對多余的括號,則構建模式將變得顯而易見: [1-9]([0-9]([0-9])?)? 另一種選擇是對[0-9]使用字符類快捷方式\\d ,從而得到[1-9]\\d{0,2}|1000

編輯:

  • 組合了比賽分組。
  • 在分子之前添加了錨點。

暫無
暫無

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

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