Scala RegEx match fails, Java one suceeds

前端 未结 1 2022
刺人心
刺人心 2020-12-02 02:32

In a following code the same pattern matches when Java API is used, but not when using Scala pattern matching.

import java.util.regex.Pattern

object Main ex         


        
相关标签:
1条回答
  • 2020-12-02 02:58

    When you define a Scala pattern, it is anchored by default (=requires a full string match), while your Java sj.find() is looking for a match anywhere inside the string. Add .unanchored for the Scala regex to also allow partial matches:

    val statePattern = statePatternString.r.unanchored
                                           ^^^^^^^^^^^
    

    See IDEONE demo

    Some UnanchoredRegex reference:

    def unanchored: UnanchoredRegex

    Create a new Regex with the same pattern, but no requirement that the entire String matches in extractor patterns.

    Normally, matching on date behaves as though the pattern were enclosed in anchors, ^pattern$.

    The unanchored Regex behaves as though those anchors were removed.

    Note that this method does not actually strip any matchers from the pattern.

    AN ALTERNATIVE SOLUTION would mean adding the .* at the pattern end, but remember that a dot does not match a newline by default. If a solution should be generic, the (?s) DOTALL modifier should be specified at the beginning of the pattern to make sure the whole string with potential newline sequences is matched.

    0 讨论(0)
提交回复
热议问题