如何使用re来搜索负数?

时间:2017-06-09 14:37:15

标签: python

我有一个打开的脚本从用户那里抓取一个整数并将其保存为results[1]

然后打开myfile.config并在字符串后搜索整数。字符串是locationID=。 所以带数字的字符串应如下所示:

locationID="34"

或任何随机数。 它用结果中的数字替换当前数字。

到目前为止,我的脚本会检查是否有号码以及locationID=后是否列出了号码。

如何检查并替换负数?

以下是原文:

def replaceid:

    source = "myfile.config"
    newtext = str(results[1])
    with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
        for line in file:
            pattern = r'(?<=locationId=")\d+'  # find 1 or more digits that come
                                              # after the string locationid     

            if re.search(pattern, line):
                sys.stdout.write(re.sub(pattern, newtext, line)) # adds number after locationid
                fileinput.close()
            else:
                sys.stdout.write(re.sub(r'(locationId=)"', r'\1"' + newtext, line)) # use sys.stdout.write instead of "print"
                # using re module to format                                                              
                # adds a location id number after locationid even if there was no number originally there        
                fileinput.close()

这对我不起作用:

def replaceid:

    source = "myfile.config"
    newtext = str(results[1])
    with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
        for line in file:
            pattern = r'(?<=locationId=")\d+'  # find 1 or more digits that come
                                              # after the string locationid     
            patternneg = r'(?<=locationId=-")\d+'

            if re.search(pattern, line):
                sys.stdout.write(re.sub(pattern, newtext, line)) # adds number after locationid
                fileinput.close()

            elif re.search(patternneg, line): # if Location ID has a negative number
                sys.stdout.write(re.sub(patternneg, newtext, line)) # adds number after locationid
                fileinput.close()   

            else:
                sys.stdout.write(re.sub(r'(locationId=)"', r'\1"' + newtext, line)) # use sys.stdout.write instead of "print"
                # using re module to format                                                              
                # adds a location id number after locationid even if there was no number originally there        
                fileinput.close()

1 个答案:

答案 0 :(得分:1)

由于您没有使用匹配的数字(无论是正数还是负数),您可以更改模式以匹配双引号.([^"]+)之间的任何内容,即使它不是数字

pattern = r'(?<=locationId=").([^"]+)'

要涵盖空""的情况,您可以将模式更改为.([^"]*)。此外,您可能希望在locationId r'(?<=locationId")\s*=\s*.([^"]*)'之前/之后有空格的情况下扩展案例的模式。