I cannot understand why my simple String equality test is returning false.
Code is:
boolean isDevelopment() {
//config.project_stage is set to "Development"
String cfgvar = "${config.project_stage}"
String comp = "Development"
assert cfgvar.equals(comp)
}
Result is:
assert cfgvar.equals(comp)
| | |
| false Development
Development
I also get false if I do:
assert cfgvar == comp
toString() is not necessary. Most probably you have some trailing
spaces in config.project_stage, so they are retained also in cfgvar.
comp has no extra spaces, what can be seen from your code.
Initially the expression "${config.project_stage}" is of GString
type, but since you assign it to a variable typed as String,
it is coerced just to String, so toString() will not change anything.
It is up to you whether you use equals(...) or ==.
Actually Groovy silently translates the second form to the first.
So, to sum up, you can write assert cfgvar.trim() == comp.
You can also trim cfgvar at the very beginning, writing:
cfgvar = "${config.project_stage}".trim()
and then not to worry about any trailing spaces.
Have you checked for trailing spaces? At least your output as one for the first Development. Try a .trim() when you compare those strings (and maybe a .toLowerCase() too)
And remember: .equals() in Groovy is a pointer comparison. What want to do is ==. Yes, just the opposite from what it is defined in Java, but the Groovy definition makes more sense :-)
Update: see comment by #tim_yates - I mixed .equals() up with .is()
On of the objects you comparing is not a String but GString, try:
cfgvar.toString().equals(comp)
However your code works with groovy v. 2.4.5. Which version are you using?
Related
I can use occursin function, but its haystack argument cannot be a regular expression, which means I have to pass the entire alphanumeric string to it. Is there a neat way of doing this in Julia?
I'm not sure your assumption about occursin is correct:
julia> occursin(r"[a-zA-z]", "ABC123")
true
julia> occursin(r"[a-zA-z]", "123")
false
but its haystack argument cannot be a regular expression, which means I have to pass the entire alphanumeric string to it.
If you mean its needle argument, it can be a Regex, for eg.:
julia> occursin(r"^[[:alnum:]]*$", "adf24asg24y")
true
julia> occursin(r"^[[:alnum:]]*$", "adf24asg2_4y")
false
This checks that the given haystack string is alphanumeric using Unicode-aware character class
[[:alnum:]] which you can think of as equivalent to [a-zA-Z\d], extended to non-English characters too. (As always with Unicode, a "perfect" solution involves more work and complication, but this takes you most of the way.)
If you do mean you want the haystack argument to be a Regex, it's not clear why you'd want that here, and also why "I have to pass the entire alphanumeric string to it" is a bad thing.
As has been noted, you can indeed use regexes with occursin, and it works well. But you can also roll your own version, quite simply:
isalphanumeric(c::AbstractChar) = isletter(c) || ('0' <= c <= '9')
isalphanumeric(str::AbstractString) = all(isalphanumeric, str)
I am a beginner in programming. I have a string for example "test:1" and "test:2". And I want to remove ":1" and ":2" (including :). How can I do it using regular expression?
Hi andrew it's pretty easy. Think of a string as if it is an array of chars (letters) cause it actually IS. If the part of the string you want to delete is allways at the end of the string and allways the same length it goes like this:
var exampleString = 'test:1';
exampleString.length -= 2;
Thats it you just deleted the last two values(letters) of the string(charArray)
If you cant be shure it's allways at the end or the amount of chars to delete you'd to use the version of szymon
There are at least a few ways to do it with Groovy. If you want to stick to regular expression, you can apply expression ^([^:]+) (which means all characters from the beginning of the string until reaching :) to a StringGroovyMethods.find(regexp) method, e.g.
def str = "test:1".find(/^([^:]+)/)
assert str == 'test'
Alternatively you can use good old String.split(String delimiter) method:
def str = "test:1".split(':')[0]
assert str == 'test'
I am working on android eclipse. This seems an easy question but I haven't found an answer of it yet! I have a string and I want to include in my if statement if that is not equal with something else. But only I know is the mystring.equals("example"). How do I enter if that string is not equal to something else? Thanks a lot
How do I enter if that string is not equal to something else?
Try this guy !. Example
if (!"someString".equals(myString)){
This tells it that if the value of myString isn't someString then it will enter the if condition. Doing it this way instead of
if (!myString.equals("someString"){
will protect against NPE so if myString is null you won't get an exception in the first example.
To be more precise, the String.equals() function is a function of return type boolean.
This means that it either returns true or false based on the values of the compared strings.
So:
if(myString.equals("other string"))
is equivalent to:
if(myString.equals("other string") == true)
To test for the contrary, you want:
if(myString.equals("other string") == false)
or the equivalent, as codeMagic mentionned: if(!myString.equals("other string"))
I have a quick question: a='Tom', a type of str. I want to make it into a set with one item. If I use the command b = set(a), I got a set with 3 items in it, which is set(['m',''T','o']). I want set(['Tom']). How could I get it? Thanks.
The set builtin makes sets out of iterables. Iterating over a string yields each character one-by-one, so wrap the string in some other iterable:
set(['Tom'])
set(('Tom',))
If you're used to the mathematical notation for sets, you can just use curly braces (don't get it confused with the notation for dictionaries):
{'Tom'}
{'Tom', 'Bob'}
The resulting sets are equivalent
>>> {'Tom'} == set(['Tom']) == set(('Tom',))
True
set(['Tom'])
You just answered your own question (give list, instead of string).
Like this:
a = "Tom"
b = set([a])
if i define a groovy variable
def x = "anish$"
it will throw me error, the fix is
def x = "anish\$"
apart form "$" what are the blacklist characters that needs to be backslash,Is there a Groovy reference that lists the reserved characters. Most “language specifications” mention these details, but I don’t see it in the Groovy language spec (many “TODO” comments).
Just use single quotes:
def x = 'anish$'
If this isn't possible, the only thing that's going to cause you problems is $, as that is the templating char used by GString (see the GString section on this page -- about half way down)
Obviously, the backslash char needs escaping as well, ie:
def x = 'anish\\'
You can use octal representation. the character $ represents 044 in octal, then:
def x = 'anish\044'
or
def x = 'anish\044'
For example, in Java i did use like this:
def x = 'anish\044'
If you wants knows others letters or symbols converters, click here :)
The solution from tim_yates does not work in some contexts, e.g. in a Jasper report.
So if still everything with a $ sign wants to be interpreted as some variable (${varX}), e.g. in
"xyz".replaceAll("^(.{4}).{3}.+$", "$1...")
then simply make the dollar sign a single concatenated character '$', e.g.
"xyz".replaceAll("^(.{4}).{3}.+"+'$', '$'+"1...")
It might be a cheap method, but the following works for me.
def x = "anish" + '$'
Another alternative that is useful in Groovy templating is ${'$'}, like:
def x = "anish${'$'}" // anish$
Interpolate the Java String '$' into your GString.