python - 如何获取字符串中另一个字符周围的一些字符?

标签 python regex string

我有:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form.

我想搜索1500s,然后选择它周围的一些字符,例如:eversince the 1500s,when anknown。考虑到我正在 for 循环中搜索,试图在一个很长的字符串中找到所有 1500 。因此,下一个循环将查找:自 1500 年代再现以来已使用

我正在使用正则表达式来查找子字符串:

substring = re.findall('1500s', string)

但是如何同时选择它周围的 20 个字符呢?

最佳答案

正如 cricket_007 所说,您可以尝试使用 .{20} 作为正则表达式模式的书挡。

substring = re.findall('.{0,20}1500s.{0,20}', s)

关于python - 如何获取字符串中另一个字符周围的一些字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45840799/

相关文章:

python - Node.js Python 外壳 : while true loop not working

python - 有没有一种快速的方法可以同时训练多个模型?

c++ - C++ 新手,使用 "=="的/字符串相等性问题

java - 如何正确使用二维数组存储多个字符串的split()结果?

python - 指定 PyYAML 转储部分的样式(二): sequences

python - TCP 连接被对等方重置且传输端点未连接

regex - 在 Git 提交消息前添加部分分支名称

javascript - 正则表达式迭代匹配多个单词

java - 用于提取键值对的正则表达式

C 编程 : declaring string and assignment