【发布时间】:2015-09-29 10:30:22
【问题描述】:
我正在尝试编写一个用于本地化源代码文件的小型 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 :-(
【问题讨论】:
-
正则表达式应该更像
/"([^"]+)"\.localized\(\)/。您不允许在Warning和.localized之间使用"。由于您使用星号组 1 将是空的。 -
尝试:
regex = re.compile(r'"([^"]*)"\.localized\(\)')并使用捕获的组 #1 -
另外,为了将来参考,这个站点非常适合测试 Python 正则表达式:pythex.org
-
@anubhava 谢谢,它工作。将其发布为答案,我会接受。
-
@Chris 你还没有接受答案。
标签: python regex string quotes between