can we check multiple patterns using regex in java?

后端 未结 2 1886
广开言路
广开言路 2021-01-13 10:13

i want to check 2 patterns using regex.

can i check those both patterns in the same time (like if(condition1 | condition2) condition).

any idea?

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-13 11:01

    It really depends - namely, you can design your regex with "or" modifiers like this "(match this)|(or this)". If you use carefully designed regex, you only need to do this:

    Pattern p1 = Pattern.compile(regex)
    Matcher m = p1.matcher(searchstring)
    

    Once. This is probably the most efficient way to go about things. The other option is to run two matcher/pattern object pairs, run find operations until find returns false than count the number of outputs. If they're both > 0 you're in business. The other option is if you only need one or more matches, to do:

    if ( matcher1.find() & matcher2.find() )
    {
        ...
    }
    

提交回复
热议问题