简体   繁体   English

如何使用 Python 中的 RegEx 使用该实例的修改版本替换匹配一个模式的多个实例?

[英]How to replace multiple instances that match one pattern, with a modified version of that instance using RegEx in Python?

In a sentence containing multiple words, separated by spaces, I have to replace does n't with doesn't .在包含多个单词,用空格隔开一个句子,我不得不更换does n'tdoesn't So I'm specifically looking for a space that occurs before a character followed by a '所以我专门寻找一个出现在字符前的空格,后跟一个'

Regex should be something like this [a-zA-z]* [a-zA-z]'[a-zA-z]正则表达式应该是这样的[a-zA-z]* [a-zA-z]'[a-zA-z]
The resulting string should be like this [a-zA-z]*'[a-zA-z]结果字符串应该是这样的[a-zA-z]*'[a-zA-z]

There could be multiple instances of the matching pattern.匹配模式可能有多个实例。 In the above example the matching pattern is s n't .在上面的例子中,匹配模式是s n't Basically I'm looking to remove the space.基本上我想删除空间。

You can make use of a positive lookbehind and lookahead to make sure you capture spaces which rest in between your conditions:您可以利用正向后视和前瞻来确保捕获介于您的条件之间的空间:

(?<=[a-zA-z]) (?=[a-zA-Z]'[a-zA-Z])

https://regex101.com/r/zUCbo0/1 https://regex101.com/r/zUCbo0/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM