簡體   English   中英

如何用正則表達式不同地替換某些正斜杠?

[英]How to replace certain forward slashes differently with regex?

可以說我有以下字符串:

this_string = 'US/Canada'

that_string = '/fowardslash @/t t/'

我希望能夠通過以下兩個目標來re.sub()字符串:

1)將之前和之后沒有字母的所有/替換為''

2)更換所有的/前,並用空格之后, 一個字母。

因此,我最終想要得到的是這樣的東西:

this_string = 'US Canada'

that_string = 'forwardslash @t t' 

我目前有這個re.sub('[^A-Za-z0-9\\s]+','', this_string)

這是第一個目標,而不是第二個。

我會得到this_string = 'USCanada'

您可以使用re.sub('\\/', ' ', this_string)作為第二個目標, \\將轉義/字符並得到所需的結果。

但是我不認為是否有可能在兩種不同的情況下使用相同的模式,您可以一起使用模式來實現所需的功能

您可以將re.sub()與自己的replace函數一起使用。

例:

import re

this_string = 'US/Canada'
that_string = '/fowardslash @/t t/'

def myreplace(match):
    if match.group(1) is not None and match.group(2) is not None:
        return match.group(1) + ' ' + match.group(2)
    else:
        return ''

print(re.sub(r'(?:([A-Za-z0-9]+)/([A-Za-z0-9]+))|(/)', myreplace, this_string))
print(re.sub(r'(?:([A-Za-z0-9]+)/([A-Za-z0-9]+))|(/)', myreplace, that_string))

也許反過來?

text = re.sub(r'\b/\b' , ' ' , text) # Replace with space
text = re.sub(r'/'     , ''  , text) # Remove

要么:

text = re.sub(r'/', '', re.sub(r'\b/\b', ' ', text))

您可以使用

import re
s = '''US/Canada
/fowardslash @/t t/'''
rx = r'(?<=[^\W\d_])/(?=[^\W\d_])|(/)'
print(re.sub(rx, lambda m: '' if m.group(1) else ' ', s))
# => US Canada
#    fowardslash @t t

在線查看Python 3演示

正則表達式匹配

  • (?<=[^\\W\\d_])/(?=[^\\W\\d_]) -一個-與任何Unicode字母包圍
  • | - 要么
  • (/) -(捕獲組1)在任何其他上下文中的/字符。

如果組1不為空,則如果匹配,則刪除匹配項,否則,將其替換為空格。

暫無
暫無

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

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