如何获取Python中的字符位置列表?
我正在尝试编写一个函数来清理 Web 应用程序中的 unicode 输入,并且目前正在尝试在本页末尾重现 PHP 函数: http://www.iamcal.com/understanding-bi Direction-text/
我正在寻找Python中PHP的preg_match_all的等效项。 RE 函数 findall 返回不带位置的匹配项,而 search 仅返回第一个匹配项。是否有任何函数可以返回我的每场比赛以及文本中的相关位置?
使用字符串 abcdefa
和模式 a|c
,我想要得到类似 [('a',0),('c',2) 的内容,('a',6)]
谢谢:)
I'm trying to write a function to sanitize unicode input in a web application, and I'm currently trying to reproduce the PHP function at the end of this page : http://www.iamcal.com/understanding-bidirectional-text/
I'm looking for an equivalent of PHP's preg_match_all in python. RE function findall returns matches without positions, and search only returns the first match. Is there any function that would return me every match, along with the associated position in the text ?
With a string abcdefa
and the pattern a|c
, I want to get something like [('a',0),('c',2),('a',6)]
Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
Try:
我不知道有什么方法可以让
re.findall
为您执行此操作,但以下方法应该可行:re.findall
查找所有匹配的字符串。str.index
查找re.findall
返回的所有字符串的关联索引。 但是,执行此操作时要小心:如果字符串在不同位置有两个精确的子字符串,则re.findall
将返回这两个子字符串,但您需要告诉 < code>str.index 表示您正在查找字符串的第二次出现或nth
出现。否则,它将返回您已有的索引。我能想到的最好方法是维护一个字典,其中将 re.findall 结果中的字符串作为键,将索引列表作为值希望这会有所帮助
I don't know of a way to get
re.findall
to do this for you, but the following should work:re.findall
to find all the matching strings.str.index
to find the associate index of all strings returned byre.findall
. However, be careful when you do this: if a string has two exact substrings in distinct locations, thenre.findall
will return both, but you'll need to tellstr.index
that you're looking for the second occurrence or thenth
occurrence of a string. Otherwise, it will return an index that you already have. The best way I can think of to do this would be to maintain a dictionary that has the strings from the result ofre.findall
as keys and a list of indices as valuesHope this helps