Regular Expression Problem in EventListener

Hello,

I have a problem when I tried to write an event listener(for DocumentCreatingEvent(), DocumentUpdatingEvent()) using Wiki Components.

method name: onEvent

The code is as follows

{{groovy}}

import java.util.regex.Pattern
import java.util.regex.Matcher

def docSource = xcontext.method.input.get(1)
def pattern = ~/\S+er\b/
def matcher = "My code is groovier and better when I use Groovy there" =~ pattern

docSource.setContent(matcher.find())

{{/groovy}}

When I updated my testing page, there was nothing printed in the page. However “true” should be expected.

Are there any suggestions?

Hello, what’s the desired outcome for you here? Do you want to update document with True statement as new content? If so - I don’t see the saving process - applying changes inside the provided code.

The patter from what I see is working, I added if/else statement for quick test and it returns Match found for me.

def pattern = ~/\S+er\b/
def matcher = "My code is groovier and better when I use Groovy there" =~ pattern

if (matcher.find()) {
   println("Match found.")
} else {
   println("No match found.")
}

As said, the “true” should be printed in my testing page, but it is not.

Saving follows the action of the event listener. It is not required here.

I knew why. It should be setContent(""+matcher.find()).

1 Like

Then why are using pattern.find()? You’re calling find method on string value, and if you look into official methods for String class StringGroovyMethods (Groovy 4.0.17) (groovy-lang.org), it expects either character, regex or pattern expression. If you want to find matches to your string it should be like this

def myPattern = ~/\S+er\b/
def myString = "My code is groovier and better when I use Groovy there"
println myString.find(myPattern)

Which will return groovier. If you expect a boolean statement, you shall use matcher.find()

The code above is just for testing. Before I begin to implement using regular expressions, I would like to know if it works.

As you pointed out, it should be matcher.find(). Thank you very much. I corrected the code above.

1 Like