简体   繁体   中英

Is java regex matcher stateful?

I come from the python side and does not know much about java regex, the question is pretty self explanatory, let me add some scenario.

Assume I have an instance with a Matcher matcher variable, and a function like this:

public String getMatch(String group) {
    if (matcher.find()) {
        return matcher.group(group);
    } else { blah }
}

Where all regex capturing groups are named, Would calling it multiple time cause problems?

  1. Yes Matcher is stateful.

  2. If anything 1 calls find or match while you are (still) looking at the groups (etc) from the previous call, then you will lose the state from the previous call. The same applies for reset and reset(CharSequence) , and some other methods. This behavior is inherent in the API design, and clearly documented.

  3. Matcher is not thread-safe. The javadoc states this explicitly:

    "Instances of this class are not safe for use by multiple concurrent threads."

  4. However, using it like your code does should work... provided that the Matcher was only visible to / used by the current thread, and not used further up (or down) the call stack.

See also:


By contrast, Pattern is both thread-safe and immutable / stateless.


1 - That could be another thread, or the current thread that is using the same Matcher at different points in the call stack; ie via recursion or something like that.

Pattern is thread-safe, but Matcher is not.

Matcher maintains some local variables like groupVars , localVars , last etc.

groupVars is used for recording group captured, it will be reset before each Matcher#match and Matcher#find operation.

localVars is used for recording the context of matching operation.

last is used by find , it represents the terminal offset of previous find operation.

If you use Matcher concurrently, those local variables will be covered by different thread, which could cause unexpected result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM