Skip to main content
 首页 » 编程设计

python之如何匹配字符串中的第一个单词

2025年05月04日35emanlee

我想匹配单词 'St' 或 'St.' 或 'st' 或 'st.' 但仅作为字符串的第一个单词。 例如 'St. Mary Church Church St.' - 应该只找到第一个 'St.'。

  • 的。 Mary Church Church St.' - 应该只找到 'st.'
  • 'st Mary Church Church St.' - 应该只找到 'st'

我想最终用“Saint”替换第一次出现的地方。

请您参考如下方法:

正则表达式 sub允许您定义要在字符串中替换的出现次数:

import re 
 
s = "St. Mary Church Church St." 
new_s = re.sub(r'^(St.|st.|St|st)\s', r'Saint ', s, 1) # the last argument defines the number of occurrences to be replaced. In this case, it will replace the first occurrence only. 
print(new_s) 
#  'Saint Mary Church Church St.'