简体   繁体   English

如何获得字符串中另一个字符周围的一些字符?

[英]How can I get some characters around another character in a string?

I have: 我有:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum只是印刷和排版行业的伪文本。 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. 自1500年代以来,Lorem Ipsum一直是行业的标准伪文本,当时一位不知名的打印机拿起一个厨房,将其打乱成一本样本书。 The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. 以下是自1500年代以来使用的Lorem Ipsum标准块。 Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form. 西塞罗(Cicero)的“ de Finibus Bonorum et Malorum”的第1.10.32和1.10.33节也照原样复制。

I want to search for 1500s and then select some characters around it, like: ever since the 1500s, when an unknown . 我想搜索1500s ,然后在其周围选择一些字符,例如: ever since the 1500s, when an unknown Considering that I am searching in a for loop, trying to find all the 1500s in a very long string. 考虑到我在for循环中搜索,试图在一个很长的字符串中查找所有1500s So the next loop would be finding: used since the 1500s is reproduced 因此,将找到下一个循环: used since the 1500s is reproduced

I am using regular expression to find the substring: 我正在使用正则表达式来查找子字符串:

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

But how to select some 20 characters around it as well? 但是,如何同时选择周围的20个字符呢?

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

substring = re.findall('.{0,20}1500s.{0,20}', s)
 r"(.{20})?(1500)(.{20})?" g

This will search for "1500" at the start/end of the string as well. 这也将在字符串的开头/结尾搜索“ 1500” I put them in groups just to tidy up the regex. 我将它们分组以便整理正则表达式。

See it work here 看到它在这里工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Python中,如何删除特定字符周围的字符? - In Python, how can I remove characters around a specific character? 如何将字符与Python中某个字符串中的所有字符进行比较? - How do I compare a character to all the characters in some string in Python? 如何打印另一个字符串中某些字符第一次出现的索引? - how can I print the index of the first occurrence of some characters in another string? 如何计算字符串中的字符数并显示字符和数量 - How can I count the number of characters in a string and displaying the character and amount 如何更改 Kivy 字符串中某些字符的偏移量? - How can I change offset for some characters in Kivy string? 如何通过匹配python中的某些字符从字符串中删除一些字符 - How to delete some characters from a string by matching certain character in python 我如何使用正则表达式获取两个字符内的字符串并删除该字符串内的某些字符 - how do i use regex to get a string inside two character and remove certain characters inside that string 如何从字符串中获取重复字符的索引? - How can I get the index of a recurring character from a string? 如何获得字符串中重复出现的字符的位置? - How can I get the position of a recurring character in a string? 如何从字符串中间获取2个字符? - How can I get 2 characters from the middle of a string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM