Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a list against a regular expression in Groovy

Tags:

regex

groovy

I have a list as below:

list1 = ["README.md", "test1.txt", "/desktop/openmpi.txt"]

I want to filter out all the file with .md and .txt extensions from this list and return me the result as boolean. So, if this list contains any .md or .txt files then return me true or if not then false.

I was trying the matcher class implementation but it did not work. I am not sure as to how can I do that with a list in one go.

My expected result is:

  1. True: If the list contains any .md or .txt files.
  2. False: If list does not contain any .md or .txt files.
like image 673
Hemant Kumar Avatar asked Oct 16 '25 19:10

Hemant Kumar


1 Answers

You may use any to see if there is an item in the list that matches a /(?i)\.(?:md|txt)$/ regex:

def list1= ["README.md", "test1.txt","/desktop/openmpi.txt"]
print(list1.any { it =~ /(?i)\.(?:md|txt)$/ } )  

Returns true.

See the Groovy demo online.

The (?i)\.(?:md|txt)$ regex matches

  • (?i) - turning case insensitivity on
  • \. - a dot
  • (?:md|txt) - a non-capturing group matching either md or txt
  • $ - end of string.
like image 74
Wiktor Stribiżew Avatar answered Oct 19 '25 15:10

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!