Python - 在字符串中定位正则表达式匹配的位置? [英] Python - Locating the position of a regex match in a string?

查看:26
本文介绍了Python - 在字符串中定位正则表达式匹配的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用正则表达式来搜索 RSS 提要,以查找是否提到了某些单词和短语,然后还想提取匹配任一侧的文本.例如:

String = "此为例句,仅供演示"搜索(是",字符串)

我想知道找到is"匹配项的位置,以便我可以提取和输出如下内容:

1 个匹配找到:这是一个例句"

我知道拆分很容易,但我需要知道字符串中匹配的第一个字符的索引是什么,我不知道如何找到

解决方案

你可以使用.find("is"),它会返回字符串中"is"的位置

或使用 .start() 来自 re

<预><代码>>>>re.search("is", String).start()2

实际上它的匹配项is"来自This"

如果需要逐词匹配,在is前后使用\b\b为词边界.

<预><代码>>>>re.search(r"\bis\b", String).start()5>>>

有关 Python 正则表达式的更多信息,请在 docs 此处

I'm currently using regular expressions to search through RSS feeds to find if certain words and phrases are mentioned, and would then like to extract the text on either side of the match as well. For example:

String = "This is an example sentence, it is for demonstration only"
re.search("is", String)

I'd like to know the position(s) of where the 'is' matches are found so that I can extract and output something like this:

1 match found: "This is an example sentence"

I know that it would be easy to do with splits, but I'd need to know what the index of first character of the match was in the string, which I don't know how to find

解决方案

You could use .find("is"), it would return position of "is" in the string

or use .start() from re

>>> re.search("is", String).start()
2

Actually its match "is" from "This"

If you need to match per word, you should use \b before and after "is", \b is the word boundary.

>>> re.search(r"\bis\b", String).start()
5
>>>

for more info about python regular expressions, docs here

这篇关于Python - 在字符串中定位正则表达式匹配的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆