source

regex 일치 배열을 만듭니다.

goodcode 2022. 9. 11. 17:12
반응형

regex 일치 배열을 만듭니다.

자바에서는 모든 regex 일치를 어레이로 되돌리려고 하는데 패턴의 일치 여부(부울)만 확인할 수 있는 것 같습니다.

regex 일치를 사용하여 특정 문자열 내의 regex 식과 일치하는 모든 문자열의 배열을 형성하려면 어떻게 해야 합니까?

(Java > = 9라고 가정할 수 있다면 4castle의 답변은 아래보다 좋습니다.)

일치 항목을 반복적으로 찾으려면 매처(matcher)를 만들고 이를 사용해야 합니다.

 import java.util.regex.Matcher;
 import java.util.regex.Pattern;

 ...

 List<String> allMatches = new ArrayList<String>();
 Matcher m = Pattern.compile("your regular expression here")
     .matcher(yourStringHere);
 while (m.find()) {
   allMatches.add(m.group());
 }

이거 끝나고allMatches일치하는 항목이 포함되어 있습니다.allMatches.toArray(new String[0])어레이가 필요한 경우 어레이를 입수할 수 있습니다.


를 사용할 수도 있습니다.MatchResult도우미 함수를 써서 매치를 루프오버하다Matcher.toMatchResult()현재 그룹 상태의 스냅샷을 반환합니다.

예를 들어, 게으른 반복자를 써서

for (MatchResult match : allMatches(pattern, input)) {
  // Use match, and maybe break without doing the work to find all possible matches.
}

이런 식으로 하는 거죠.

public static Iterable<MatchResult> allMatches(
      final Pattern p, final CharSequence input) {
  return new Iterable<MatchResult>() {
    public Iterator<MatchResult> iterator() {
      return new Iterator<MatchResult>() {
        // Use a matcher internally.
        final Matcher matcher = p.matcher(input);
        // Keep a match around that supports any interleaving of hasNext/next calls.
        MatchResult pending;

        public boolean hasNext() {
          // Lazily fill pending, and avoid calling find() multiple times if the
          // clients call hasNext() repeatedly before sampling via next().
          if (pending == null && matcher.find()) {
            pending = matcher.toMatchResult();
          }
          return pending != null;
        }

        public MatchResult next() {
          // Fill pending if necessary (as when clients call next() without
          // checking hasNext()), throw if not possible.
          if (!hasNext()) { throw new NoSuchElementException(); }
          // Consume pending so next call to hasNext() does a find().
          MatchResult next = pending;
          pending = null;
          return next;
        }

        /** Required to satisfy the interface, but unsupported. */
        public void remove() { throw new UnsupportedOperationException(); }
      };
    }
  };
}

이와 함께.

for (MatchResult match : allMatches(Pattern.compile("[abc]"), "abracadabra")) {
  System.out.println(match.group() + " at " + match.start());
}

수율

a at 0
b at 1
a at 3
c at 4
a at 5
a at 7
b at 8
a at 10

Java 9에서는 를 사용하여 일치 목록/배열을 가져올 수 있습니다.

import java.util.regex.Pattern;
import java.util.regex.MatchResult;
String[] matches = Pattern.compile("your regex here")
                          .matcher("string to search from here")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
                    // or .collect(Collectors.toList())

Java는 regex를 너무 복잡하게 만들고 perl 스타일을 따르지 않습니다.MentaRegex에서 Java 코드의 한 줄에서 이를 실현하는 방법을 확인하십시오.

String[] matches = match("aa11bb22", "/(\\d+)/g" ); // => ["11", "22"]

다음은 간단한 예입니다.

Pattern pattern = Pattern.compile(regexPattern);
List<String> list = new ArrayList<String>();
Matcher m = pattern.matcher(input);
while (m.find()) {
    list.add(m.group());
}

(더 많은 캡처 그룹이 있는 경우 인덱스로 그룹 방식의 인수로 참조할 수 있습니다.어레이가 필요한 경우list.toArray())

공식 정규 정규 Java Trail에서:

        Pattern pattern = 
        Pattern.compile(console.readLine("%nEnter your regex: "));

        Matcher matcher = 
        pattern.matcher(console.readLine("Enter input string to search: "));

        boolean found = false;
        while (matcher.find()) {
            console.format("I found the text \"%s\" starting at " +
               "index %d and ending at index %d.%n",
                matcher.group(), matcher.start(), matcher.end());
            found = true;
        }

사용하다find그리고 그 결과를 삽입한다.group당신의 배열/목록/뭐든지 간에.

        Set<String> keyList = new HashSet();
        Pattern regex = Pattern.compile("#\\{(.*?)\\}");
        Matcher matcher = regex.matcher("Content goes here");
        while(matcher.find()) {
            keyList.add(matcher.group(1)); 
        }
        return keyList;

언급URL : https://stackoverflow.com/questions/6020384/create-array-of-regex-matches

반응형