Python 如何使用re搜索负数?

Python 如何使用re搜索负数?,python,Python,我有一个脚本,打开后从用户那里获取一个整数,并将其保存为结果[1] 然后打开myfile.config并在字符串后搜索整数。字符串是locationID=。 因此,带有数字的字符串应该如下所示: locationID="34" 或者随便什么随机数。 它用结果中的数字替换当前数字 到目前为止,我的脚本检查在locationID=之后是否有数字以及是否没有列出数字 如何检查并替换负数 这是原件: def replaceid: source = "myfile.config" ne

我有一个脚本,打开后从用户那里获取一个整数,并将其保存为
结果[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(结果[1])
将fileinput.fileinput(source,inplace=True,backup='.bak')作为文件:
对于文件中的行:

pattern=r'(?因为您没有使用匹配的数字(无论是正数还是负数),所以可以更改模式以匹配双引号([^“]+)
之间的任何内容,即使它不是数字

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

pattern=r'(?您是否尝试过类似re.sub(“locationId=([-\d]+)”、newtext、line)的方法?“locationId=\”(?\d+\”同时匹配locationId=“34”和locationId=“-34”“并将编号作为组。您可以在此处进行验证:如何将其输入模式变量?这将完全删除文档中的locationid字符串:模式='locationid=\”(?\d+)”“我的问题是,它把我的‘else’语句弄乱了,在locationid之后添加了一个location id编号,即使原来没有编号
pattern = r'(?<=locationId=").([^"]+)'