I am studying the zero-width RegEx. First, I test my pattern and text at http://testregex.com/ and it works well. Then I test them in my Java program, but they don't match. So I'd like to make it clear the cause of problem. Any reply would be appreciated. Thanks!
pattern:`\w*(?=ing)`
text:
I’m singing while you’re dancing
Java code:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo {
public static void main(String[] args) {
RegexDemo demo = new RegexDemo();
System.out.printf("%b%n", demo.zeroWidthAssertionEarly());
}
public boolean zeroWidthAssertionEarly()
{
String reg="\\w*(?=ing)";
String word = "I’m singing while you’re dancing";
boolean tem=false;
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(word);
tem = matcher.matches();
return tem;
}
}
Thank you in advance. Now I hope I do better understand the difference between match() and find(), and I modified my code as follows:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo {
public static void main(String[] args) {
RegexDemo demo = new RegexDemo();
System.out.printf("%b%n", demo.zeroWidthAssertionEarly());
}
public boolean zeroWidthAssertionEarly()
{
//匹配以ing结尾的单词
String reg="\\w*(?=ing)";
String word = "I’m singing while you’re dancing";//
boolean tem=false;
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(word);
while(matcher.find()){
System.out.printf("start = %d%n", matcher.start());
System.out.printf("end = %d%n", matcher.end());
}
return tem;
}
}
Its output confused me:
start = 4
end = 8
start = 8
end = 8
start = 25
end = 29
start = 29
end = 29
false
So my new question is: Why the output is not as follows?
start = 4
end = 8
start = 25
end = 29
false
matches()requires a full string match. Tryfind(). BTW, you have not indicated what you need to get as a result. Just true or false?