source

정규식 일치 후에 이어지는 텍스트 가져오기

itover 2022. 12. 1. 21:28
반응형

정규식 일치 후에 이어지는 텍스트 가져오기

Regex를 처음 사용하는데다 튜토리얼을 많이 읽어봤지만 내가 하고 싶은 일에 맞는 튜토리얼을 찾지 못했어요.

검색 문자열 자체가 아닌 검색 문자열 뒤에 있는 모든 항목을 반환하고 싶다.

: "어느 정도 재미없는 문장이 멋지다"

검색, 검색, 검색, 검색, 검색, 검색, 검색, 검색, 검색, 검색 등

"그거 대박이다"라고 답하다

어떤 도움이라도 주시면 감사하겠습니다.

지금까지의 제 정규식입니다.

sentence(.*) 

하지만 돌아온다: 멋진 문장

Pattern pattern = Pattern.compile("sentence(.*)");

Matcher matcher = pattern.matcher("some lame sentence that is awesome");

boolean found = false;
while (matcher.find())
{
    System.out.println("I found the text: " + matcher.group().toString());
    found = true;
}
if (!found)
{
    System.out.println("I didn't find the text");
}

코멘트에서 요구한 대로 "정규 표현만"으로 이 작업을 수행할 수 있습니다.

(?<=sentence).*

(?<=sentence)긍정적인 이면 어설션입니다.이것은 문자열의 특정 위치, 즉 텍스트 바로 뒤의 위치에서 일치합니다.sentence그 텍스트 자체를 일치시키지 않고 말이죠.그 결과,(?<=sentence).*다음 텍스트와 일치합니다.sentence.

이것은 regex의 꽤 좋은 기능입니다.단, Java에서는 유한 길이의 서브 표현식, 즉 유한 길이의 서브 표현식에 대해서만 동작합니다.(?<=sentence|word|(foo){1,4})합법이지만(?<=sentence\s*)그렇지 않아요.

정규식"sentence(.*)"맞아요.괄호 안의 그룹의 내용을 취득하려면 , 다음의 콜을 실시합니다.

Pattern p = Pattern.compile( "sentence(.*)" );
Matcher m = p.matcher( "some lame sentence that is awesome" );
if ( m.find() ) {
   String s = m.group(1); // " that is awesome"
}

의 사용에 주의해 주세요.m.find()이 경우(스트링상의 임의의 위치를 찾을 수 없음) 및m.matches()('some lame' 프리픽스로 인해 실패합니다.이 경우 regex는".*sentence(.*)")

Matcher가 초기화된 경우str매치 후에, 이 부품을 취득할 수 있습니다.

str.substring(matcher.end())

샘플 코드:

final String str = "Some lame sentence that is awesome";
final Matcher matcher = Pattern.compile("sentence").matcher(str);
if(matcher.find()){
    System.out.println(str.substring(matcher.end()).trim());
}

출력:

대박이다

matcher의 group(int)을 사용해야 합니다.group(0)은 일치하고 group(1)은 처음에 표시한 그룹입니다.지정한 예에서 group(1)은 "sentence" 뒤에 오는 것입니다.

다음 행에 "group()" 대신 "group(1)"을 입력하면 원하는 대로 반환됩니다.

System.out.println("I found the text: " + matcher.group(**1**).toString());

언급URL : https://stackoverflow.com/questions/5006716/getting-the-text-that-follows-after-the-regex-match

반응형