python - 嵌套方括号
问题描述
我有这样的模式:
word word one/two/three word
我想匹配由/
. 我的想法如下:
[\w]+ # match any words
[\w]+/[\w]+ # followed by / and another word
[\w]+[/[\w]+]+ # repeat the latter
但这不起作用,因为我似乎一添加]
,它就不会关闭内部的摩西,[
而是最外部的[
。
如何使用嵌套方括号?
解决方案
这是使用的一种选择re.findall
:
import re
input = "word word one/two/three's word apple/banana"
r1 = re.findall(r"[A-Za-z0-9'.,:;]+(?:/[A-Za-z0-9'.,:;]+)+", input)
print(r1)
["one/two/three's", 'apple/banana']
演示
推荐阅读
- r - 如何在标签集之后添加水平线而不在 RMarkdown 的 TOC 中创建空白条目?
- c - 是否有编译器选项可用于将堆栈变量初始化为非零值(毒药)以帮助调试?
- gekko - Gekko 非线性混合整数规划。设置目标函数的问题
- bash - 将文件的权限(八进制)与 Bash Shell 中的整数进行比较
- email - 如果我的域中不存在电子邮件地址,则创建它
- wordpress - Elementor 中的响应式文本大小、图像大小和布局
- php - 下单后缺货时自动为产品添加特定类别和标签
- spring - 在 Spring Batch 中的步骤之间传递值时出现空指针异常
- linux - Ubuntu 20.4 中的 Ncurses 是否与 18.04 中的版本不兼容
- r - 如何在 Docker 映像中安装 R 库“ggpubr”?