![](/img/trans.png)
[英]Python Regex: How to extract string between parentheses and quotes if they exist
[英]Python regex get string between quotes
我正在尝试编写一个小的python脚本来本地化源代码文件。
在源文件中,有一些这样的字符串:
title: "Warning".localized()
我想做的就是每当找到一个附加的.localized()
时都提取引号之间的字符串。
匹配此字符串的正则表达式为: regex = re.compile('([^"]*).localized\\(\\)', re.DOTALL)
匹配有效,因为我得到以下输出:
...
./testproject/test1.swift
.localized()
.localized()
./testproject/test2.swift
...
但是我没有得到引号之间的字符串。
python脚本:
import os, re, subprocess
import fnmatch
def fetch_files_recursive(directory, extension):
matches = []
for root, dirnames, filenames in os.walk(directory):
for filename in fnmatch.filter(filenames, '*' + extension):
matches.append(os.path.join(root, filename))
return matches
regex = re.compile('([^"]*).localized\(\)', re.DOTALL)
for file in fetch_files_recursive('.', '.swift'):
print file
with open(file, 'r') as f:
content = f.read()
# e.g. "Warning".localized(),
for result in regex.finditer(content):
print result.group(0) // output = '.localized()'
print result.group(1) // output = '' empty :-(
将我的评论转换为答案。
您可以使用以下模式:
regex = re.compile(r'"([^"]*)"\.localized\(\)')
并使用捕获的#1组。 [^"]*
匹配非双引号的0个或多个字符。
或使用环境:
regex = re.compile(r'(?<=")([^"]*)"(?="\.localized\(\)'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.