![](/img/trans.png)
[英]Python Regex: Extract all occurences of a substring within a string
[英]Put all occurences in the String in quotes using regex in python
我有一個很長的字符串,我可以找到這樣的東西data() { <some data which is always different here> }
我想把所有出現的都放在引號中。 這是我正在做的,但沒有效果:
string = re.sub(r'data \(\) {(.*)}', r'"/1"', string)
我想大括號之間應該有什么不同,但我不知道是什么......
@EDIT我意識到我的字符串看起來像這樣:
data() {
<some white spaces> here is text
<some white spaces> }
空格很重要,斜線的方向很重要(感謝 Wiktor,我之前忽略了這一點)並且這個量詞可能應該是懶惰的。 此外,如果您的文本中有換行符,您需要允許
string = re.sub(r'(?s)data\(\) {(.*?)}', r'"\1"', string)
在您的示例文本上測試它:
In [4]: string = """data() {
...: <some white spaces> here is text
...: <some white spaces> }"""
In [5]: print(re.sub(r'(?s)data\(\) {(.*?)}', r'"\1"', string))
"
<some white spaces> here is text
<some white spaces> "
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.