4

java 如何线程安全的循环匹配正则表达式

 2 years ago
source link: https://www.oschina.net/question/2303434_2324080
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

java 如何线程安全的循环匹配正则表达式

码上中国博客 发布于 昨天 18:22

我目前的代码如下:

public static String getFirstPhoneNum(String phoneNumer) {
        List<String> regs = Lists.newArrayList("400\\d{7}(-\\d{4}|转\\d{4})?|400-\\d{3}-\\d{4}(-\\d{4}|转\\d{4})?\",\"1\\d{10}"
                , "1\\d{10}",
                "\\d{8}(-\\d{1,4}[^\\d]$)?|\\d{3}-?\\d{8}(-\\d{1,4}[^\\d]$)?|\\d{4}-?\\d{7,8}(-\\d{1,4}[^\\d]$)?|\\d{3,4}-?\\d{4}-?\\d{4}(-\\d{1,4}[^\\d]$)?");
        List<Integer> indexes = new ArrayList<>();
        for (String reg : regs) {
            boolean b = Pattern.matches(reg, phoneNumer);
            Pattern pattern = Pattern.compile(reg);
            Matcher matcher = pattern.matcher(phoneNumer);
            matcher.reset(phoneNumer); //TODO 是否会线程不安全
            Integer index = matcher.groupCount();
            if (matcher.find() && index > 0) {
                String phone = matcher.group(0);
                ......
            }
        }
        ......
        return "-";
    }

以上方法每个http请求会调用多次,发现在该方法调用量多的时候会造成线程不安全,看官方资料说Matcher线程不安全,请问我该如何写才能线程安全的完成上述循环匹配的业务。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK