Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find if groovy args contains a particular string

Tags:

groovy

println args

println args.size()

println args.each{arg-> println arg}

println args.class

if (args.contains("Hello"))
    println "Found Hello"

when ran give following error:

[hello, somethingelse]
2
hello
somethingelse
[hello, somethingelse]
class [Ljava.lang.String;
Caught: groovy.lang.MissingMethodException: No signature of method: [Ljava.lang.
String;.contains() is applicable for argument types: (java.lang.String) values:
[Hello]

why can I not do contains?

like image 903
groovynoob Avatar asked Mar 12 '10 16:03

groovynoob


People also ask

How do you check if a substring is present in a string in Groovy?

Groovy - contains() Checks if a range contains a specific value.

How do I check if a string contains?

The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.

How do you check if a list contains a value in Groovy?

Groovy - Lists contains() Returns true if this List contains the specified value.


2 Answers

Because args is String[] but not List<String>

You can use

if (args.grep('Hello'))
    println "Found Hello"
like image 131
Mykola Golubyev Avatar answered Sep 19 '22 15:09

Mykola Golubyev


That's because args is an array of String (just like in Java) and not a String, take a look at the result of:

print args.getClass()

>>class [Ljava.lang.String;

Notice the [L notation.

A regular String would result in:

>>class java.lang.String

The Groovy containers do not have the contains() operation (String does), yet the java.lang.Object of Groovy SDK has the grep() operation (shown on the first reply).

like image 39
3 revs Avatar answered Sep 19 '22 15:09

3 revs