Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何正确构建正则表达式?_Python_Re - Fatal编程技术网

Python 如何正确构建正则表达式?

Python 如何正确构建正则表达式?,python,re,Python,Re,我不知道问题出在哪里,也不知道为什么我的日常工作不起作用 with open('output.csv', 'w') as outFile: for line in fileone: if re.match(r'\"C:\\Program Files \(x86\)\\Google\\Chrome\\Application\\chrome\.exe\" --type',line): pass else:

我不知道问题出在哪里,也不知道为什么我的日常工作不起作用

with open('output.csv', 'w') as outFile:
    for line in fileone:
        if re.match(r'\"C:\\Program Files \(x86\)\\Google\\Chrome\\Application\\chrome\.exe\" --type',line):
            pass
        else:
            if line not in filetwo:
                outFile.write(line)
abowe代码应匹配以下所有行并传递:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --type
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --type
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --type
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --type
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --type
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --type
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --type
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --type
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --type

您的用例不需要正则表达式,因为您有一个公共字符串。相反,您可以使用
str.startwith()
来匹配字符串是否以任何特定字符串开头。例如:

>>> "my string".startswith("my")
True

>>> "my string".startswith("string")
False
因此,您的代码将成为:

with open('output.csv', 'w') as outFile:
    for line in fileone:
        #       vvvvvvvvv updated here
        if line.startswith('"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --type'):
            pass
        else:
            if line not in filetwo:
                outFile.write(line)
或者可以简化为:

my_string = '"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --type'

with open('output.csv', 'w') as outFile:
    for line in fileone:
        if not line.startswith(my_string) and line not in filetwo:
            outFile.write(line)

每次都是相同的字符串,为什么需要正则表达式?我们不能在条件检查过程中直接比较字符串内容吗?不,有很长的不同字符串-
if line.startswith(“'C:\ProgramFiles(x86)\Google\Chrome\Application\Chrome.exe”--type”):
我试过了,但不起作用。如果
line.startswith(''C:\ProgramFiles(x86)\Google\Chrome\Application\Chrome.exe'“--type'):
如果我需要做很多异常,这对我来说不是最好的解决方案。@test_qweqwe但你不需要基于你在问题中提到的异常。如果您有其他要求,请在问题中提及。否则,我们将很难处理您的所有用例