python - 如何用下划线搜索和替换这个空白?
问题描述
text = 'Captain Fawcett英国 美国'
'Captain' 和 'Fawcett' 之间有一个空格,我想用下划线替换这个空格:
text = 'Captain_Fawcett英国'
替换条件是前面和后面的char是[a-zA-Z]。我想在 Python 中做这样的事情:
pattern = '[a-zA-Z](\s)[a-zA-Z]'
text = re.sub(pattern, "_", text)
但这并没有得到我想要的。
解决方案
利用
re.sub(r'(?<=[a-zA-Z])\s+(?=[a-zA-Z])', '_', s)
见证明。
解释
--------------------------------------------------------------------------------
(?<= look behind to see if there is:
--------------------------------------------------------------------------------
[a-zA-Z] any character of: 'a' to 'z', 'A' to 'Z'
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
\s+ whitespace (\n, \r, \t, \f, and " ") (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
[a-zA-Z] any character of: 'a' to 'z', 'A' to 'Z'
--------------------------------------------------------------------------------
) end of look-ahead
推荐阅读
- javascript - 如何通过单击标记隐藏标记并放大指定的地图位置?
- ios - 关于自定义 URL 方案传输数据的方式
- python - 如何从一堆 URL 中提取 URI?
- html - 如何使用 HTML 和 CSS 将选项卡和子选项卡转换为下拉项和子项
- javascript - 如何从 IP 列表中找到最近的 IP?
- sql - 获取仅与给定值列表关联的 id
- javascript - 如何提取多维数组中每个子数组的第一个元素?
- java - 无法将方法与 MainActivity 类分开
- openid - 去中心化 ID (DID) 相对于联合身份的优势
- java - 升级 java/jsf 应用程序时出现问题,日期时间转换器不再工作