Here I have following Groovy-example looking for a match (product value) from the example text below.
def text = "This is my example text and it contains CD-12. Text continues after that."
def product = "CD-10"
if (text.contains("CD-12")) {
println ("Match was found!")
}
else {
println ("No match! Using default product " + product)
}
IF-block is executed as a direct match (CD-12) is found from the example text.
I have two additions that I have been investigating but so far have not succeeded.
Addition 1, dynamically changing product in the text
The first one is that let's imagine the number section for the product part CD-XX of text would change so that it would be anything between CD-1 - CD-99 (CD- remains not changing, only numbers following it would change) or that the part CD-XX would not exist at all in text.
If not existing then ELSE-block would be executed and default product printed (like my current ELSE-block) but otherwise the product variable would be replaced by matched value found from text (for example: CD-13).
I think there most likely is a regex way since it seems that contains does not allow regex?
Addition 2, in case of multiple matches only take the latest one for product value
If text was modified like this:
def text = "This is my example text and it contains CD-12. Text continues after that and here is also CD-15"
Then only the latest match (CD-15 in this case) would be taken as value for product.
EDIT: It seems like I got the first part (Addition 1) working like this:
def text = "This is my example text and it contains CD-12. Text continues after that. Text also contains CD-14"
def product = "CD-10"
// This line contains regex which looks for match from the text
def matches = text =~ "CD-\\d{1,2}"
println "Default product is: CD-10"
if (matches) {
println "Match was found!"
match = matches[0]
println "Match is: " + match
product = match
println "Updated product is: " + match
}
else {
println "No match"
println "Product is the default value: " + product
}
In case of match this prints:
Default product is: CD-10
Match was found!
Match is: CD-12
Updated product is: CD-12
So as match was found from the text the default product got updated. If CD-parts are removed from the text meaning no match, following gets printed:
Default product is: CD-10
No match
Product is the default value: CD-10
Remaining challenge:
What I am still looking for is how to only take the latest value in case of multiple matches (CD-14 as the latter in this updated example text).
just take the last match -
[-1]in groovythis will print
CD-15