簡體   English   中英

Python Regex:匹配前面或后面沒有帶數字的單詞的字符串

[英]Python Regex: Match a string not preceded by or followed by a word with digits in it

我想在 Python 中使用正則表達式來替換前面或后面沒有帶數字的單詞的字符串。

IE

對於下面的句子,

今天是4月4日。 她的名字是四月 明天是 4 月 5 日。

我只想匹配四月(粗體)並將其替換為“人”,結果應如下所示:

今天是4月4日。 她的名字是的人 明天是 4 月 5 日。

我嘗試使用這個正則表達式:

(\w*(?<!\w*\d\w*\s)April(?!\s\w*\d\w*))

但是,我有一個錯誤說:

error: look-behind requires fixed-width pattern

任何幫助表示贊賞。

這是您可以使用的一種正則表達式:

(?:^\s+|[^\w\s]+\s*|\b[^\d\s]+\s+)(April)\b(?!\s*\w*\d)

設置大小寫無關標志。 目標詞在捕獲組 1 中捕獲。

演示

Python 的正則表達式引擎執行以下操作:

(?:           # begin non-cap grp
  ^           # match beginning of line
  \s*         # match 0+ whitespace characters
  |           # or
  [^\w\s]+    # match 1+ chars other than word chars and whitespace
  \s*         # match 0+ whitespace chars
  |           # or
  \b          # match word break
  [^\d\s]+    # match 1+ chars other than digits and whitespace
  \s+         # match 1+ whitespace chars
)             # end non-cap grp  
(April)       # match 'April' in capture group
\b            # match word break
(?!           # begin negative lookahead
  \s*         # match 0+ whitespace chars         
  \w*         # match 0+ word chars
  \d          # match a digit
)             # end negative lookahead

我所采取的方法是指定什么可能在"April"之前以及為什么不能緊隨其后。 我無法指定什么不能在"April"之前,因為這需要負向后視,而 Python 的正則表達式引擎不支持這種情況。

我假設"April"可能會:

  • 位於字符串的開頭,可能后跟空格;
  • 前面是一個既不是單詞字符也不是空格的字符,后面可能有空格; 或者
  • 前面是一個不包含數字的單詞,后面可能跟空格。

我還假設"April"后面跟着一個分詞,后面可能沒有包含數字的單詞,前面可能有空格。

可以使用支持可變長度后視的 Pypi 正則表達式庫來完成。

import regex

str = 'Today is 4th April. Her name is April. Tomorrow is April 5th.'
res = regex.sub(r'(?<!\d[a-z]* )April(?! [a-z]*\d)', 'PERSON', str)
print(res)

輸出:

Today is 4th April. Her name is PERSON. Tomorrow is April 5th.

解釋:

(?<!\d[a-z]* )      # negative lookbehind, make sure we haven't a digit followed by 0 or more letters and a space before
April               # literally
(?! [a-z]*\d)       # negative lookahead, make sure we haven't a space, 0 or more letters and a digit after

使用re模塊更新:

import re

str = 'Today is 4th April. Her name is April. Tomorrow is April 5th.'
res = re.sub(r'(\b[a-z]+ )April(?! [a-z]*\d)', '\g<1>PERSON', str)
print(res)

暫無
暫無

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

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