IT이야기

regex를 사용하여 서브스트링을 추출하는 방법

cyworld 2022. 6. 16. 22:20
반응형

regex를 사용하여 서브스트링을 추출하는 방법

두 개의 작은 따옴표가 있는 문자열이 있는데'성격.작은 따옴표 사이에 내가 원하는 데이터가 있다.

다음 텍스트에서 "원하는 데이터"를 추출하기 위해 정규식을 작성하려면 어떻게 해야 합니까?

mydata = "some string with 'the data i want' inside";

작은 따옴표 사이에 있는 부분을 사용하는 경우 다음 정규 표현을 사용합니다.

"'(.*?)'"

예:

String mydata = "some string with 'the data i want' inside";
Pattern pattern = Pattern.compile("'(.*?)'");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find())
{
    System.out.println(matcher.group(1));
}

결과:

내가 원하는 데이터

이 일에 정규식은 필요없어

프로젝트에 apache commons lang(http://commons.apache.org/proper/commons-lang/),을 추가한 후 다음을 사용합니다.

String dataYouWant = StringUtils.substringBetween(mydata, "'");
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile(".*'([^']*)'.*");
        String mydata = "some string with 'the data i want' inside";

        Matcher matcher = pattern.matcher(mydata);
        if(matcher.matches()) {
            System.out.println(matcher.group(1));
        }

    }
}

여기에는 다음과 같은 간단한 단서가 있습니다.

String target = myData.replaceAll("[^']*(?:'(.*?)')?.*", "$1");

일치하는 그룹을 옵션으로 함으로써 이 경우 공백이 반환되어도 따옴표를 찾을 수 없습니다.

라이브 데모를 봐 주세요.

여러 따옴표로 묶인 문자열을 쉽게 처리할 수 있는 regex가 없는 솔루션인 Scala도 선택했기 때문입니다.

val text = "some string with 'the data i want' inside 'and even more data'"
text.split("'").zipWithIndex.filter(_._2 % 2 != 0).map(_._1)

res: Array[java.lang.String] = Array(the data i want, and even more data)
String dataIWant = mydata.replaceFirst(".*'(.*?)'.*", "$1");

Java 9 이후

이 버전에서는 arg가 없는 새로운 방법을 사용하여 쾌적하게 반환할 수 있습니다.Stream<MatchResult>여기서 는 일치 조작의 결과를 나타내며 일치된 그룹 등을 읽습니다(이 클래스는 Java 1.5 이후 인식되고 있습니다).

String string = "Some string with 'the data I want' inside and 'another data I want'.";

Pattern pattern = Pattern.compile("'(.*?)'");
pattern.matcher(string)
       .results()                       // Stream<MatchResult>
       .map(mr -> mr.group(1))          // Stream<String> - the 1st group of each result
       .forEach(System.out::println);   // print them out (or process in other way...)

위의 코드 스니펫은 다음과 같습니다.

the data I want
another data I want

가장 큰 장점은 절차와 비교하여 하나 이상의 결과를 얻을 수 있을 때 사용이 용이하다는 것입니다.if (matcher.find())그리고.while (matcher.find())체크 및 처리.

javascript:

mydata.match(/'([^']+)'/)[1]

실제 regexp는 다음과 같습니다./'([^']+)'/

(다른 투고와 같이) 욕심이 없는 수식어를 사용하면 다음과 같습니다.

mydata.match(/'(.*?)'/)[1]

그것은 더 깨끗하다.

String dataIWant = mydata.split("'")[1];

라이브 데모 보기

Apache Commons Lang은 java.lang API를 위한 다수의 도우미 유틸리티, 특히 String 조작 방법을 제공합니다.당신의 경우 시작과 끝의 서브스트링이 같기 때문에 다음 함수를 호출하기만 하면 됩니다.

StringUtils.substringBetween(String str, String tag)

동일한 문자열의 두 인스턴스 사이에 중첩된 문자열을 가져옵니다.

시작과 끝의 서브스트링이 다를 경우 다음과 같은 오버로드 방법을 사용합니다.

StringUtils.substringBetween(String str, String open, String close)

두 문자열 사이에 중첩된 문자열을 가져옵니다.

일치하는 서브스트링의 모든 인스턴스를 원하는 경우 다음을 사용합니다.

StringUtils.substringsBetween(String str, String open, String close)

String에서 시작 태그와 종료 태그로 구분된 하위 문자열을 검색하여 배열 내의 일치하는 하위 문자열을 모두 반환합니다.

해당 예에서는 일치하는 하위 문자열의 모든 인스턴스를 가져옵니다.

String[] results = StringUtils.substringsBetween(mydata, "'", "'");

스칼라에서는

val ticks = "'([^']*)'".r

ticks findFirstIn mydata match {
    case Some(ticks(inside)) => println(inside)
    case _ => println("nothing")
}

for (ticks(inside) <- ticks findAllIn mydata) println(inside) // multiple matches

val Some(ticks(inside)) = ticks findFirstIn mydata // may throw exception

val ticks = ".*'([^']*)'.*".r    
val ticks(inside) = mydata // safe, shorter, only gets the first set of ticks

i loop을 사용하여 어레이 내의 모든 일치 서브스트링을 저장할 수 있습니다.

if (matcher.find()) { System.out.println(matcher.group(1)); }

matchs 서브스트링을 사용하여 모든 match 서브스트링을 얻을 수 있습니다.

Matcher m = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+").matcher(text);
   // Matcher  mat = pattern.matcher(text);
    ArrayList<String>matchesEmail = new ArrayList<>();
        while (m.find()){
            String s = m.group();
            if(!matchesEmail.contains(s))
                matchesEmail.add(s);
        }

    Log.d(TAG, "emails: "+matchesEmail);

pom.xml에 apache.xml 의존관계 추가

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>

아래 코드는 유효합니다.

StringUtils.substringBetween(String mydata, String "'", String "'")

그룹이 나에게 어떻게 작용하지 않았는가.group(0)을 사용하여 URL 버전을 검색했습니다.

Pattern urlVersionPattern = Pattern.compile("\\/v[0-9][a-z]{0,1}\\/");
Matcher m = urlVersionPattern.matcher(url);
if (m.find()) { 
    return StringUtils.substringBetween(m.group(0), "/", "/");
}
return "v0";

언급URL : https://stackoverflow.com/questions/4662215/how-to-extract-a-substring-using-regex

반응형