그루비 및 정규식 일치 그룹 문제
다음과 같은 다른 질문과 예제를 읽은 후 여기에 왔습니다.
정규식 일치를위한 Groovy 구문
그루비 정규식 / 패턴 매칭
또한 온라인에서 찾은이 문서 : https://e.printstacktrace.blog/groovy-regular-expressions-the-definitive-guide/
나는 그것을 가지고 놀고 있었고 나는 매우 기본적인 정규식이라고 생각하는 것을 가지고 있지만 어떤 이유로 나는 항상 일치하지 않습니다.
그래서 "ssh : //[email protected]/project/repo.git"과 같은 git URL이 있다고 상상해보십시오.
내 그루비 파이프 라인에서 프로젝트와 리포지토리 자체를 추출하고 싶습니다. "ssh : //[email protected]/ ([a-zA-Z- ] *) / ([a-zA-Z- ] *) .git "(이 일치를 수행하는 더 현명한 방법이 있지만 여전히 작동해야 함)
어쨌든 문제는 내가 이것을 테스트하고 있으며 현재는 간단한 ssh 일치도 만들 수 없다는 것입니다. 온라인 정규식 테스터에서 잘 작동합니다.

그러나 온라인 그루비 놀이터에서는 작동하지 않습니다.
이것이 예입니다 (여기서 테스트하고 있습니다 https://groovy-playground.appspot.com/) :
이 입력 :
GIT_URL='ssh://[email protected]/project/repo.git'
def match = GIT_URL =~ /ssh:\/\/git@bitbucket\.sits\.net\/([a-zA-Z-_]*)\/([a-zA-Z-_]*)\.git/
println match
일치하지 않는 출력 :
java.util.regex.Matcher[pattern=ssh://git@bitbucket\.sits\.net/([a-zA-Z-_]*)/([a-zA-Z-_]*)\.git region=0,45 lastmatch=]
몇 가지 시도했지만 ssh 일치도 작동하지 않습니다.
GIT_URL='ssh://[email protected]/project/repo.git'
def match = GIT_URL =~ /ssh/
println match
java.util.regex.Matcher[pattern=ssh region=0,45 lastmatch=]
도구에서 문제가 될 수 있다고 생각했지만 Jenkins 파이프 라인에서도 작동하지 않습니다.
또한 다른 질문의 예 :
def match2 = "f1234" =~ /[a-z]\d{4}/
println match2
java.util.regex.Matcher[pattern=[a-z]\d{4} region=0,5 lastmatch=]
답변
Groovy가 올바른 matcher 메서드를 실행하도록 둘 수 있습니다.
String GIT_URL='ssh://[email protected]/project/repo.git'
def match = GIT_URL =~ /ssh:\/\/git@bitbucket\.sits\.net\/([a-zA-Z_-]*)\/([a-zA-Z_-]*)\.git/
if (match) {
println match[0][1]
println match[0][2]
} else {
println 'No match'
}
Groovy 데모를 참조하십시오.
로 =~
와 운영자, 실제로, 긴 문자열 내에서 부분 일치를 찾을 수 그루비에게 ==~
, 당신은 전체 문자열 일치를 필요로한다. 필요한 것은 if (match)
일치를 트리거하는 것입니다. 에 match
모든 일치 항목이 포함되므로 0 번째 색인을 통해 첫 번째 항목을 얻은 다음을 사용하여 그룹 1 [1]
과 그룹 2에 액세스 할 수 있습니다 [2]
.
정규식 팁 : -
리터럴 -
문자 와 일치 시키 려면 항상 문자 클래스의 끝에 넣으십시오 .
이것은 실제로 내가 기대했던 것이 아니었지만 메서드가 match () 호출하는 것을 잊었습니다.
GIT_URL='ssh://[email protected]/project/repo.git'
def match = GIT_URL =~ /ssh:\/\/git@bitbucket\.sits\.net\/([a-zA-Z-_]*)\/([a-zA-Z-_]*)\.git/
match.matches()
println match.group(1)
println match.group(2)
project
repo