Skip to content

Using ==~ with Pattern.compile loses flags #2298

@maczikasz

Description

@maczikasz

Describe the bug

When using the ==~ operator and passing a compiled Pattern instance with flags set, Spock replaces the object with a new Pattern object but uses only the regex string not the flags.

This is confusing because using the ==~ in plain groovy works

To Reproduce

import spock.lang.Specification
import java.util.regex.Pattern

class PatternBugSpec extends Specification {

    def "Pattern.DOTALL is lost in direct assertion - BUG"() {
        given:
        def text = "foo\nBar\nfoo"  // Multi-line string
        def pattern = Pattern.compile(".*Bar.*", Pattern.DOTALL)  // DOTALL to match across newlines

        expect: "This FAILS because Spock loses the DOTALL flag"
        text ==~ pattern
    }

    def "Workaround: assign to boolean first - WORKS"() {
        given:
        def text = "foo\nBar\nfoo"
        def pattern = Pattern.compile(".*Bar.*", Pattern.DOTALL)

        // This WORKS because Groovy handles the match, creating a boolean
        def match = text ==~ pattern

        expect: "This PASSES"
        match
    }
}

More examples in:

https://github.com/maczikasz/spock-pattern-settings

Expected behavior

I expect that the flags are preserved or if it's not supported to use Pattern instances, then there shoudl be some feedback from the test

Actual behavior

Silently fails the assert

Java version

211

Buildtool version

gradle 9.2

What operating system are you using

Mac

Dependencies

not relevant

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions