Python 在引号之间的文件中查找文本

标签 python

我正在 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/

相关文章:

python结构解压

python - 初始化中……命令 'sox'返回了非零的退出状态2

python - 从字节串到 Python 中的 OpenCV 的 IplImage?

python - 在我的 Python 笔记本中使用 Matplotlib 时出现黑色图表

python - 使用 plotnine 更改刻度标签

python - 在python中对名称列表进行排序

python 脚本 envoke -h 或 --help 如果没有选择任何选项

python - 如何从 Flask 中的配置文件导入?

python - 如何在每第 n 次出现空格但重叠时拆分字符串

python - 如何在Python中设置魔术方法的默认行为?