( জাভা> = 9 ধরে নিতে পারলে নীচের চেয়ে 4 ক্যাসলের উত্তরগুলি আরও ভাল)
আপনাকে ম্যাচার তৈরি করতে হবে এবং পুনরাবৃত্তভাবে মিলগুলি খুঁজে পেতে এটি ব্যবহার করতে হবে।
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