[英]A way of stripping everything before and after ' or " (including the quotes themselves)
我试图找到一种方法来去除单引号或双引号之前或之后的所有内容,包括引号本身。
例如:
<script src = "https://example.com/file.js"></script>
结果:
https://example.com/file.js
要么:
url = 'https://example.com/service/api'
结果:
https://example.com/service/api
我已经尝试过使用.strip
和.replace
以及re
库,但是我在黑暗中掌握了这一点。
在这里使用HTML解析库是不好的,因为我们事先不知道代码是哪种语言。 我们正在搜索文本行以查找URL,然后将URL本身发送到另一个API。 这可以是文本文件,yaml,json,java,c#,python,ruby等。
与其尝试删除目标字符串之前和之后的所有内容,不如将其视为提取目标字符串而不是其周围上下文。
使用正则表达式匹配组提取带引号的字符串:
import re
string = '<script src = "https://example.com/file.js"></script>'
match = re.search("(\".+?\"|'.+?')", string)
target = match.group(1).strip("\"'")
target
等于https://example.com/file.js
。
re.search()
中的正则表达式匹配"somestring"
或'somestring'
。 括号之间的组的内容可以使用match.group(1)
提取。 然后,我们使用strip()
删除任一侧的引号。
您可能想使用类似
if match:
target = match.group(1).strip("\"'")
因为如果正则表达式不匹配,则match
将为None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.