如何从行中找到字符串(“原样”-没有子字符串)?

时间:2018-09-15 13:57:18

标签: regex string python-3.x match

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

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

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

3 个答案:

答案 0 :(得分:2)

首先标记您的file变量

tokens = file.split()

然后寻找您的令牌

if token in tokens:
    # do your thing

答案 1 :(得分:0)

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

( function( ownerDocument ) {
    //...
    if( method === "document.currentScript.ownerDocument.createElement") {
        imgEl = ownerDocument.createElement("img")
        var imgOK = document.adoptNode( imgEl )
    }
    //...  
} ) ( document.currentScript.ownerDocument )

答案 2 :(得分:0)

尝试使用正则表达式

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!"