【问题标题】:regex: word index in string正则表达式:字符串中的单词索引
【发布时间】:2020-05-27 06:38:05
【问题描述】:

给定一个大字符串:

str = "Include all the information someone would need to answer your question ... ..."

如何仅通过python代码和正则表达式(而不是列表等)来获取该字符串中整个单词的索引;如果它是列表中的元素,则此索引是该单词的索引:

lst = str.split() 

其中:“信息”一词的索引为3,“答案”的索引为8。

【问题讨论】:

  • 你能否更详细地解释一下这个问题。
  • 你的意思是str.split().index('information')?为什么要用re 模块重新发明轮子?

标签: python regex indexing substring word


【解决方案1】:

不知道您为什么要以这种方式返回您的Index,但可能类似于:

Indx = re.findall(r'^.*\binformation\b', str)[0].count(' ')

或:

Indx = re.search(r'^.*\binformation\b', str).group(0).count(' ')

这将返回单词信息的位置/索引。

【讨论】:

  • 如果我需要所有职位怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-17
  • 2011-01-05
  • 1970-01-01
  • 2011-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多