문제

Regex에 문제가 있습니다. 내 코드는 다음과 같습니다.

 self.file = re.sub(r'([^;{}]{1}\s*)[\n]|([;{}]\s*[\n])',r'\1\2',self.file)
.

이를 대체해야합니다 :

TJumpMatchArray *skipTableMatch         
);        
void computeCharJumps(string *str
.

다음과 같이 :

TJumpMatchArray *skipTableMatch     );
void computeCharJumps(string *str
.

흰색 공백을 저장하고 {}이 아닌 모든 새로운 줄 '\ n'을 대체해야합니다.'' '.

문제는 Python이 Parallen이 작동하지 않고 첫 번째 그룹과 일치하지 않으면이 문제로 실패 할 경우 다음과 같이 해석 할 수 있습니다.

File "cha.py", line 142, in <module>
maker.editFileContent()
File "cha.py", line 129, in editFileContent
self.file = re.sub(r'([^;{}]{1}\s*)[\n]|([;{}]\s*[\n])',r'\1|\2',self.file)
File "/usr/local/lib/python3.2/re.py", line 167, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/usr/local/lib/python3.2/re.py", line 286, in filter
return sre_parse.expand_template(template, match)
File "/usr/local/lib/python3.2/sre_parse.py", line 813, in expand_template
raise error("unmatched group")
.

이 온라인 regex 도구에서는 여기

이유가있는 이유 :

|([;{}]\s*[\n])
.

가 있다면 :

';        \n'
.

대체 :

'        \n'
.

''{} 후에 동일한 형식을 저장해야합니다.

이 문제를 해결할 수있는 방법이 있습니까?

도움이 되었습니까?

해결책

문제는 모든 발견 된 모든 일치 만 하나의 그룹이 비어 있지 않습니다.

이 단순화 된 예를 고려하십시오.

>>> import re
>>> 
>>> def replace(match):
...     print(match.groups())
...     return "X"
... 
>>> re.sub("(a)|(b)", replace, "-ab-")
('a', None)
(None, 'b')
'-XX-'
.

보시다시피, 두 번째 그룹이 None로 설정된 두 번째 그룹과 한 번씩 한 번씩 대체 기능을 두 번 호출하고 첫 번째로 한 번 호출됩니다.

함수를 사용하여 일치 항목을 대체하는 경우 (예 : 내 예제와 같은) 그룹 중 어느 것을 일치하는지 쉽게 확인할 수 있습니다.

예 :

re.sub(r'([^;{}]{1}\s*)[\n]|([;{}]\s*[\n])', lambda m: m.group(1) or m.group(2), self.file)
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top