Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python正则表达式在引号之间获取字符串_Python_Regex_String_Quotes_Between - Fatal编程技术网

Python正则表达式在引号之间获取字符串

Python正则表达式在引号之间获取字符串,python,regex,string,quotes,between,Python,Regex,String,Quotes,Between,我正在尝试编写一个用于本地化源代码文件的小型python脚本 在源文件中有一些字符串,例如: title: "Warning".localized() 每当我发现一个.localized()附件时,我要做的就是提取引号之间的字符串 匹配此字符串的正则表达式是:regex=re.compile('([^“]*).localized\(\'),re.DOTALL) 匹配有效,因为我得到以下输出: ... ./testproject/test1.swift .localized() .localiz

我正在尝试编写一个用于本地化源代码文件的小型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个或多个

或使用arounds:

regex = re.compile(r'(?<=")([^"]*)"(?="\.localized\(\)'))

regex=re.compile(r')(?regex应该更像
/”([^“]+)“\.localized\(\)/
。在
警告
.localized
之间不允许使用
>。由于使用星号组,1将为空。请尝试:
regex=re.compile(r')([^“]*)“\.localized”(\))
并使用捕获的组#1另外,为了将来的参考,此站点非常适合测试Python正则表达式:@anubhava谢谢,它成功了。将其作为答案发布,我会接受的。@Chris你还没有接受答案。