我正在 try catch 引号内的文本并将它们设置为变量,以便我在以后更改它们。我知道如何在 bash shell 中执行此操作,但我不知道如何在 Python 中执行此操作。
我已经开始这样做了,但我希望有人能指出我的错误所在。
import re
input = open(filename, 'r')
quotes = re.findall(r'"[^"]*"', input.read(), re.U)
print quotes
遗憾的是,这个输出:
['"test1"', '"test2"']
当我在寻找:
value1 = test1
value2 = test2
在 Bash 中我使用了这个(但我显然不能这样使用它!):
i=0
regex='"([^"]*)"'
while read line
do
if [[ $line =~ $regex ]]; then
printf -v "text$i" '%s' "${BASH_REMATCH[1]}"
i=$((i + 1))
fi
done < filename
echo "value1: $text0"
echo "value2: $text1"
最佳答案
使用非捕获组 (?:...)
,像这样:
In [18]: re.findall('(?:")([^"]*)(?:")', '''hello "foo" "bar" haha''')
Out[18]: ['foo', 'bar']
或者使用非消费组(?<=...)
等:
In [14]: re.findall('(?<=")[^"]*(?=")', '''hello "foo" "bar" haha''')
Out[14]: ['foo', ' ', 'bar']
后者有一个同时选择 " "
的副作用在 "foo"
之间和 "bar"
.
关于Python 在引号之间的文件中查找文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34155110/