1

Guys I have the following case:

def AllEnviroments = ['company-test', 'MYTEST-1234', 'company-somethingelse-something']
def EnviromentChoices = (AllEnviroments =~  /company-.*|MYTEST/).findAll().collect().sort()

How to exclude from this regex strings that have ” something ” or whatever it will be in it's place inside it so it will print only company test and DPDHLPA

Expected result : PRINT company-test and mytest-1234 and NOT "company-something"

WhoAmI
  • 1,013
  • 2
  • 9
  • 19

1 Answers1

1

You can use

def AllEnviroments = ['company-test', 'MYTEST-1234', 'company-somethingelse-something']
def EnviromentChoices = AllEnviroments.findAll { it =~ /company-(?!something).*|MYTEST/ }.sort()
print(EnviromentChoices)
// => [MYTEST-1234, company-test]

Note that the .findAll is run directly on the string array where the regex is updated with a negative lookahead to avoid matching any strings where something comes directly after company-.

See the Groovy demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • That works, what I failed to mention and added to my question is that it is not always sure if it will be company-something, it could company-onething-secondthing-anotherthing. I always to exclude based on a specific word – WhoAmI Sep 16 '21 at 12:51
  • @WhoAmI So, the `something` should not be at the end of string? Remove `$` from the lookahead, see updated demo at https://ideone.com/mNH8VL – Wiktor Stribiżew Sep 16 '21 at 12:58
  • One question is just for the sake can it be better. Is there a way to make the same regex, but not rely on the "-". Just check if anywhere in the string "something" exists – WhoAmI Sep 16 '21 at 13:50
  • @WhoAmI I think you mean `/^(?!.*something).*(?:company-|MYTEST)/` – Wiktor Stribiżew Sep 16 '21 at 13:51
  • You are my hero. Wish I understood better how this works: ^(?!.*something).* . But that is exactly what was needed. Thanks a lot – WhoAmI Sep 16 '21 at 15:33
  • @WhoAmI It is one of the most common regexps. See [this](https://stackoverflow.com/a/57301144/3832970). – Wiktor Stribiżew Sep 16 '21 at 15:38
  • Why does your code work with findAll(it =~) , but not def EnviromentChoices = (AllEnviroments =~ /company-(?!something|another|other).*|DPDHLPA-.*/ ).findAll().collect().sort() . I receive null result like that. Groovy is so confusing :D – WhoAmI Sep 17 '21 at 07:46
  • @WhoAmI Nothing confusing here, a regex can only be applied to a *string*. Your `AllEnviroments` is a *list* or *array*. So, it is coerced to a string before the regex can start looking for matches. And it is not what you want. You want to apply the regex on each item in the array and only get those that match. – Wiktor Stribiżew Sep 17 '21 at 08:16