【问题标题】:How to search for a particular word using regular expression in python?如何在python中使用正则表达式搜索特定单词?
【发布时间】:2018-04-30 20:35:19
【问题描述】:

我进行了很多搜索,但无法找到解决问题的方法,即我想从输入(文本)中搜索特定单词。虽然我只找到第一个字母。 我的代码如下:

import re

regex = r"([a-zA-Z]+)"
datm = str(input('Enter  a passage to search for a word :'))
if re.search(regex, datm):

    match = re.search(regex, datm)

    print("Full match: %s" % (match.group(0)))

else:

    print("The regex pattern does not match. :(")

谢谢你的回答,如果你要给减号,你不必回答。

【问题讨论】:

  • \btheparticularword\b(在此之前检查str.split(在str.strip的帮助下)就足够了)。
  • 您是否尝试在某些给定文本中搜索单词?现在看起来你只是在尝试检查用户是否输入了一个单词。如果你想搜索一些文本,你会从哪里得到文本?
  • 有些不聪明的人会给出减号,尽管我警告过他们,但这会阻碍我提问和学习。我需要帮助而不是减号。
  • 让您的问题清晰且可回答,您将获得支持。根本不清楚你的问题是什么。您要匹配的单词有什么特别之处?为什么你认为你需要正则表达式?也许你只需要datm = str(input('Enter a passage to search for a word :')) 然后print(datm)
  • 如果[a-zA-Z]+ 按顺序排列,则匹配多个字母。

标签: python regex python-2.7 if-statement


【解决方案1】:

这对我有用,也许你应该试一试。

import re
xx = str(input('Enter your text '))
richWord1 = re.findall(r"^\w+",xx) #finding the first word
print (richWord1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-10
    • 2015-03-16
    • 2021-04-20
    • 1970-01-01
    • 2013-06-10
    • 2022-07-14
    • 1970-01-01
    • 2020-01-25
    相关资源
    最近更新 更多