English 中文(简体)
Java Regex Thread是否安全?
原标题:Is Java Regex Thread Safe?
  • 时间:2009-09-01 01:04:18
  •  标签:

我有以下功能:<代码>Pattern#compile和Matcher,以寻找一种模式的示意图清单。

这一功能用于多个深层。 每个校对将有一个独一无二的模式,在构造时,可采用<条码>。 深层和格局是动态的,这意味着我可以增加<条码>。 配置期间, 模式和校对。

如果使用规章,我是否有必要就这一职能提出<条码>。 j是否安全?

最佳回答
问题回答

Java 定期表达

总结:

The Java regular expression API has been designed to allow a single compiled pattern to be shared across multiple match operations.

You can safely call Pattern.matcher() on the same pattern from different threads and safely use the matchers concurrently. Pattern.matcher() is safe to construct matchers without synchronization. Although the method isn t synchronized, internal to the Pattern class, a volatile variable called compiled is always set after constructing a pattern and read at the start of the call to matcher(). This forces any thread referring to the Pattern to correctly "see" the contents of that object.

On the other hand, you shouldn t share a Matcher between different threads. Or at least, if you ever did, you should use explicit synchronization.

总而言之,你可以重复(在固定变量中加以控制)所汇编的模式,并告诉他们,如果需要的话,可以给你新的匹配者,以验证这些对一些扼杀物的reg。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Validation helpers
 */
public final class Validators {

private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,})$";

private static Pattern email_pattern;

  static {
    email_pattern = Pattern.compile(EMAIL_PATTERN);
  }

  /**
   * Check if e-mail is valid
   */
  public static boolean isValidEmail(String email) { 
    Matcher matcher = email_pattern.matcher(email);
    return matcher.matches();
  }

}

见http://zoomicon.wordpress.com/ 2009/06/01/validating-e-mails-using-table-expressions-in-java/“rel=“nofollow”http://zoomicon.wordpress.com/2007/06/01/validating-e-mails-using-table-expressions-in-java/。 关于上文用于确认电子邮件的RegEx模式(如果它符合电子邮件确认的需要,则在此张贴)





相关问题
热门标签