![](/img/trans.png)
[英]How can I use use a regex to match characters that aren't included in certain words?
[英]Python regex: Line can't start with certain words, can only contain certain characters
我正在從文件中讀取行,我想刪除僅包含字母,冒號,括號,下划線,空格和反斜杠的行。 這個正則表達式可以很好地找到這些行...
[^A-Za-z0-9:()_\s\\]
...作為原始字符串傳遞給re.search()。
現在,我需要補充一點,即行不能以THEN或ELSE開頭; 否則,它們不應匹配,因此可以免除。
我試着只是將^移出括號,並在帶括號的表達式前添加一個負數后面,就像這樣...
r'^(?!(ELSE|THEN))[A-Za-z0-9:()_\s\\]'
...但是現在它只匹配每一行。 我想念什么?
只需使用一個交替:
^(?:THEN|ELSE|[A-Za-z0-9:()_\s\\]*$)
並刪除與模式不匹配的行。
^(?:(?:.*[^A-Za-z0-9:()_\s\\])|(?:THEN|ELSE)).*$
分解
^(?: ).*$ # Starts with
(?: )|(?: ) # Either
.*[^A-Za-z0-9:()_\s\\] # Anything that contains a non-alphanumeric character
THEN|ELSE # THEN/ELSE
請參閱regex101.com上的示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.