jcat
jcat

Reputation: 5

Regex in Groovy to accept multiple lines

I am trying to get my script to accept comments that are "approved" or "Approved", etc. Whenever a user approves they may have some signature in the comment which is causing the script to not run.

Here is my regex thus far:

 def regexStr = /^[A|a][P|p][P|p][R|r][O|o][V|v][E|e][D|d]?/

Anyone know what I should add to this to have it accept new lines?

Thanks.

Upvotes: 0

Views: 2984

Answers (1)

Tidhar Klein Orbach
Tidhar Klein Orbach

Reputation: 2966

Using (?s) will cause the . to include new line character Here is an example:

def exp = /(?s)([A|a][P|p][P|p][R|r][O|o][V|v][E|e][D|d])(.*)/
def approve = '''approved my signature
Approved new signature
APPROVED old signature
apprOved'''
approve.find(exp)

EDIT: In the solution above it would just select everything from the first find to the end. therefore, here is a better solution (using (?i) as @cfric suggested in the comments):

def exp = /(?mi)^approved/
def approve = '''approved my signature
Approved new signature
APPROVED old signature
apprOved'''
def m = approve =~ exp
m.eachWithIndex{ match, idx ->
    println "m[${idx}] = ${match}"
}

output:

m[0] = approved
m[1] = Approved
m[2] = APPROVED
m[3] = apprOved

explanation:

  • (?m) - multi-line support modifier. In that case the '.' would not match new line character. so any line would be checked separatly.
  • (?i) - match case insensitive
  • ^ - beginning of a line

so each line that begins with "approved" in any letter case, would match that expression. optionally, you can add .* at the end: /(?mi)^approved.*/ to match the text after. "approved". in that case the output would be:

m[0] = approved my signature
m[1] = Approved new signature
m[2] = APPROVED old signature
m[3] = apprOved

Upvotes: 3

Related Questions