Programing

정규식 일치 배열 만들기

lottogame 2020. 6. 21. 19:40
반응형

정규식 일치 배열 만들기


Java에서는 모든 정규 표현식 일치를 배열로 반환하려고하지만 패턴이 일치하는지 (부울) 만 확인할 수있는 것 같습니다.

정규식 일치를 사용하여 주어진 문자열의 정규식과 일치하는 모든 문자열의 배열을 어떻게 구성 할 수 있습니까?


( Java> = 9라고 가정하면 4castle의 대답 이 아래보다 낫습니다.)

매처를 작성하고이를 사용하여 반복적으로 일치하는 항목을 찾아야합니다.

 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

In Java 9, you can now use Matcher#results() to get a Stream<MatchResult> which you can use to get a list/array of matches.

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 makes regex too complicated and it does not follow the perl-style. Take a look at MentaRegex to see how you can accomplish that in a single line of Java code:

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

Here's a simple example:

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

(if you have more capturing groups, you can refer to them by their index as an argument of the group method. If you need an array, then use list.toArray())


From the Official Regex Java Trails:

        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;
        }

Use find and insert the resulting group at your array / List / whatever.


        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

반응형