【问题标题】:how to find string ("as is" - no substring) from line?如何从行中查找字符串(“原样” - 无子字符串)?
【发布时间】:2018-09-15 13:57:17
【问题描述】:

我是 python 新手,想做以下事情:

  1. 在文本中搜索以检查令牌是否存在
  2. token 不能是文本内的子字符串 - 必须是“原样”(string11111 不是 string1)

    file = "string11111 aaaaa string1 bbbbb"
    token = "string1"
    
    if token in file:
        print "NOT yay!"
    
  3. 需要从结束位置到开始(反向)搜索令牌

【问题讨论】:

  • 您能否详细说明一下列表中最后一项的含义?如果您只是检查令牌是否在更大的字符串中,那么您搜索的方向并不重要(目标是否找到)。您是否希望在结果中获得更多信息,例如所有比赛或最后一场比赛的位置?您的令牌是否总是一个简单的字符串,而不是某种模式(例如正则表达式)?
  • 你需要最后一项的索引吗?

标签: regex string python-3.x match


【解决方案1】:

首先标记您的 file 变量

tokens = file.split()

然后寻找你的令牌

if token in tokens:
    # do your thing

【讨论】:

  • 没有优雅的方法吗?如果令牌是“string1”并且令牌 [0] 是“string111”,它将匹配......那不是我要找的
  • @user1596023,我不相信答案中的代码符合您的想法。 'string111' 不等于 'string1' 所以它不会匹配(即它不会执行 'do your thing')。但是,这不会反向搜索,这是您的另一个要求。
  • 好吧,如果您使用的是您提供的示例,则有一个“string1”标记。所以这显然会找到匹配项,对吧?
【解决方案2】:

希望以下解决方案能够满足您的需求 -

file = "string11111 aaaaa string1 bbbbb"
token = "string1"

token_matched = [file_token for file_token in file.split()[::-1] if token in file_token and len(token) == len(file_token)]

print('Matched tokens (reverse order) - ', token_matched)
if len(token_matched) > 1:
    # Reoccurs more than one time which means the token could be sub-string
    print("NOT yay!")
elif len(token_matched) == 1:
    # Matches only time definitely it could not be the sub-string
    print("OHH yay!")
else:
    print("Token not exist in file.")

【讨论】:

  • 我想检查 string1 是否存在并忽略 string11111,它们确实都包含令牌,但只有 string1 是确切的字符集。
【解决方案3】:

试试这个,使用正则表达式

file = "string11111 aaaaa string1 bbbbb"[::-1]
token = "string1"
regex = r"\b" + re.escape(token) + r"\b"
match = re.findall(regex , file)[0]

if match in file:
    print "NOT yay!"

【讨论】:

    猜你喜欢
    • 2021-03-19
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2011-07-13
    • 2023-01-19
    • 2012-09-07
    相关资源
    最近更新 更多