[Q#16817031][A#16817458] How to iterate over regex expression
https://stackoverflow.com/q/16817031
Let's say I have the following String: I want to find all matches of name=value and make sure that the whole string matches the pattern. So I did the following: Ensure that the whole pattern matches what I want. Iterate over the pattern name=value Is there some way to do this with one regex?
Answer
https://stackoverflow.com/a/16817458
You can validate and iterate over matches with one regex by: Ensuring there are no unmatched characters between matches (e.g. name1=x;;name2=y;) by putting a \G at the start of our regex, which mean "the end of the previous match". Checking whether we've reached the end of the string on our last match by comparing the length of our string to Matcher.end(), which returns the offset after the last character matched. Something like: Live demo. Some languages might allow you to iterate over the individual matches directly from ^((\w+)=(\w+);)*$, but I don't believe you can do this in Java.
APIzation
String line = "name1=gil;name2=orit;";
Pattern p = Pattern.compile("\\G(\\w+)=(\\w+);");
Matcher m = p.matcher(line);
int lastMatchPos = 0;
while (m.find()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
lastMatchPos = m.end();
}
if (lastMatchPos != line.length())
System.out.println("Invalid string!");
package com.stackoverflow.api;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Human16817458 {
public static boolean isStringValid(String line) {
Pattern p = Pattern.compile("\\G(\\w+)=(\\w+);");
Matcher m = p.matcher(line);
int lastMatchPos = 0;
while (m.find()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
lastMatchPos = m.end();
}
if (lastMatchPos != line.length()) return false;
return true;
}
}
package com.stackoverflow.api;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* How to iterate over regex expression
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/16817458">https://stackoverflow.com/a/16817458</a>
*/
public class APIzator16817458 {
public static void iterate(String line) throws Exception {
Pattern p = Pattern.compile("\\G(\\w+)=(\\w+);");
Matcher m = p.matcher(line);
int lastMatchPos = 0;
while (m.find()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
lastMatchPos = m.end();
}
if (lastMatchPos != line.length()) System.out.println("Invalid string!");
}
}