첫 번째 정규식과 일치하는 문자열 반환
정규식의 첫 번째 일치를 얻고 싶습니다.
이 경우 목록이 있습니다.
text = 'aa33bbb44'
re.findall('\d+',text)
[ '33', '44']
목록의 첫 번째 요소를 추출 할 수 있습니다.
text = 'aa33bbb44'
re.findall('\d+',text)[0]
'33'
하지만 일치하는 항목이 하나 이상있는 경우에만 작동합니다. 그렇지 않으면 오류가 발생합니다.
text = 'aazzzbbb'
re.findall('\d+',text)[0]
IndexError : 목록 색인이 범위를 벗어났습니다.
이 경우 함수를 정의 할 수 있습니다.
def return_first_match(text):
try:
result = re.findall('\d+',text)[0]
except Exception, IndexError:
result = ''
return result
새로운 함수를 정의하지 않고 그 결과를 얻을 수있는 방법이 있습니까?
''다음을 추가하여 정규식에 기본값을 포함 할 수 있습니다 |$.
>>> re.findall('\d+|$', 'aa33bbb44')[0]
'33'
>>> re.findall('\d+|$', 'aazzzbbb')[0]
''
>>> re.findall('\d+|$', '')[0]
''
re.search다른 사람 이 지적한 것과 도 작동 합니다.
>>> re.search('\d+|$', 'aa33bbb44').group()
'33'
>>> re.search('\d+|$', 'aazzzbbb').group()
''
>>> re.search('\d+|$', '').group()
''
첫 번째 일치 만 필요한 경우 다음 re.search대신 사용하십시오 re.findall.
>>> m = re.search('\d+', 'aa33bbb44')
>>> m.group()
'33'
>>> m = re.search('\d+', 'aazzzbbb')
>>> m.group()
Traceback (most recent call last):
File "<pyshell#281>", line 1, in <module>
m.group()
AttributeError: 'NoneType' object has no attribute 'group'
그런 다음 다음 m과 같은 검사 조건으로 사용할 수 있습니다 .
>>> m = re.search('\d+', 'aa33bbb44')
>>> if m:
print('First number found = {}'.format(m.group()))
else:
print('Not Found')
First number found = 33
You shouldn't be using .findall() at all - .search() is what you want. It finds the leftmost match, which is what you want (or returns None if no match exists).
m = re.search(pattern, text)
result = m.group(0) if m else ""
Whether you want to put that in a function is up to you. It's unusual to want to return an empty string if no match is found, which is why nothing like that is built in. It's impossible to get confused about whether .search() on its own finds a match (it returns None if it didn't, or an SRE_Match object if it did).
I'd go with:
r = re.search("\d+", ch)
result = return r.group(0) if r else ""
re.search only looks for the first match in the string anyway, so I think it makes your intent slightly more clear than using findall.
You can do:
x = re.findall('\d+', text)
result = x[0] if len(x) > 0 else ''
Note that your question isn't exactly related to regex. Rather, how do you safely find an element from an array, if it has none.
Maybe this would perform a bit better in case greater amount of input data does not contain your wanted piece because except has greater cost.
def return_first_match(text):
result = re.findall('\d+',text)
result = result[0] if result else ""
return result
참고URL : https://stackoverflow.com/questions/38579725/return-string-with-first-match-regex
'IT Share you' 카테고리의 다른 글
| Windows 작업 스케줄러를 사용하여 PowerShell 스크립트를 자동으로 실행하려면 어떻게해야합니까? (0) | 2020.11.30 |
|---|---|
| Elixir에서 기능을 나열 할 모듈을 얻을 수있는 방법이 있습니까? (0) | 2020.11.30 |
| distutils : 사용자 정의 매개 변수를 setup.py에 전달하는 방법은 무엇입니까? (0) | 2020.11.30 |
| Azure 저장소 위치에 하위 컨테이너를 만드는 방법 (0) | 2020.11.30 |
| Page.User.Identity.IsAuthenticated는 FormsAuthentication.SignOut () 후에도 여전히 true입니다. (0) | 2020.11.30 |