I'm learning regex and I have this fragment of code:
private static final String FILE_BEGINNING_PATTERN = "^(,Share %)";
public static void main(String[] args) {
String str = ",Share %,\"Date Purchased\",Display Name,Address,Phone,Fax,Mobile,Email,";
Matcher beginningFileMatcher = Pattern.compile(FILE_BEGINNING_PATTERN).matcher(str);
if (beginningFileMatcher.find()) {
System.out.println("Regex match!");
}
// find() method starts at the beginning of this matcher's region, or, if
// a previous invocation of the method was successful and the matcher has
// not since been reset, at the first character not matched by the previous
// match.
//
int count = 0;
while (beginningFileMatcher.find()) { // find not match, we need beginningFileMatcher.reset() but its not
// thread-safe.
count++;
System.out.println("COUNT ++++++++++++++ :" + count);
}
}
try another way:
private static final String FILE_BEGINNING_PATTERN = "^(,Share %)";
public static void main(String[] args) {
String s = ",Share %,\"Date Purchased\",Display Name,Address,Phone,Fax,Mobile,Email,";
Pattern beginningFilePattern = Pattern.compile(FILE_BEGINNING_PATTERN);
Matcher matcher = beginningFilePattern.matcher(s);
if (beginningFilePattern.matcher(s).find()) {
System.out.println("Thread-safe regex match!.");
}
int countCount = 0;
while (beginningFilePattern.matcher(s).find()) { //this cause infinite loop while matcher.find() done as
// expected result! Why?
countCount++;
System.out.println("COUNT ++++++++++++++ :" + countCount);
}
}
I already comment on that problem in this snippet as above. Is there anyone who can explain why? Thank you so much!
if, whywhile?if (beginningFilePattern.matcher(s).find())countCountshould be initialized to1if the firstifblock is true.Threadclass, throughExecutorServiceand related classes or by using Swing) will you have to worry about thread safety. But even then an object that you create and use within a single method is only used from a single thread. (Another thread could execute that same method at the same time, but that other thread would create and use it's own object.)