I'm getting an error when I try to use an if/else statement in Xcode 6 with Swift. This is what I have
} else if countElements(sender.text) == 1, 2
It's telling me:
Type 'String!' does not conform to protocol '_CollectionType'
How can I compare two values on one line?
You can use "||" = "or"
} else if countElements(sender.text) == 1 || countElements(sender.text) == 2 {
}
The other answer correctly shows the way to make 2 comparisons in Swift, but this can be done in a single statement thanks to Swift's pattern matching operator. For example:
if 1...2 ~= countElements(sender.text) {
println("count is 1 or 2")
}
Basically, the provided statement is true if the number of characters in your string is inclusively between 1 and 2.
You can also use the contains global function, providing it a range and the element to check for inclusion:
contains(1...2, countElements(sender.text))
Related
I have a string:
s='articles[zone.id=1].comments[user.status=active].user'
Looking to split (via split(some_regex_here)). The split needs to occur on every period other than those inside the bracketed substring.
Expected output:
["articles[zone.id=1]", "comments[user.status=active]", "user"]
How would I go about this? Or is there something else besides split(), I should be looking at?
Try this,
s.split(/\.(?![^\[]*\])/)
I got this result,
2.3.2 :061 > s.split(/\.(?![^\[]*\])/)
=> ["articles[zone.id=1]", "comments[user.status=active]", "user"]
You can also test it here:
https://rubular.com/r/LaxEFQZJ0ygA3j
I assume the problem is to split on periods that are not within matching brackets.
Here is a non-regex solution that works with any number of nested brackets. I've assumed the brackets are all matched, but it would not be difficult to check that.
def split_it(s)
left_brackets = 0
s.each_char.with_object(['']) do |c,a|
if c == '.' && left_brackets.zero?
a << '' unless a.last.empty?
else
case c
when ']' then left_brackets -= 1
when '[' then left_brackets += 1
end
a.last << c
end
end.tap { |a| a.pop if a.last.empty? }
end
split_it '.articles[zone.id=[user.loc=1]].comments[user.status=active].user'
#=> ["articles[zone.id=[user.loc=1]]", "comments[user.status=active]", "user"]
I'm at a loss why the following code doesn't work. The intention is to input a vector of strings, some of which can be converted to a number, some can't. The following 'sapply' function should use a regex to match numbers and then return the number or (if not) return the original.
sapply(c("test","6","-99.99","test2"), function(v){
if(grepl("^[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?$",v)){as.numeric(v)} else {v}
})
Which returns the following result:
"test" "6" "-99.99" "test2"
Edit: What I expect the code to return:
"test" 6 -99.99 "test2
I can run the if statement on each element successfully.
> if(grepl("^[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?$","test")){as.numeric("test")} else {"test"}
[1] "test"
if(grepl("^[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?$","6")){as.numeric("6")} else {"6"}
[1] 6
And etc...
I don't understand why this is happening. I guess I have two questions. One: Why is this happening? And two: Usually I'm pretty good at troubleshooting, but I have no idea where to even look for this. If you know the problem, how did you find/know the solution? Should I open up the internal lapply function code?
that happens because sapply returns a vector, and a vector can't be mixed. If you use lapply then you get a list result which can be mixed, the same code but with lapply instead of sapply works how you want it to.
#Jeremy points into right direction, you can use lapply, which returns a list. Or, you can tell sapply not to simplify result.
If simplification occurs, the output type is determined from the
highest type of the return values in the hierarchy NULL < raw <
logical < integer < double < complex < character < list < expression,
after coercion of pairlists to lists.
out <- sapply(c("test","6","-99.99","test2"), function(v){
if(grepl("^[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?$",v)){
as.numeric(v)
} else {
v
}
}, simplify = FALSE)
> out
$test
[1] "test"
$`6`
[1] 6
$`-99.99`
[1] -99.99
$test2
[1] "test2"
I am using ColdFusion 9.0.1.
I am trying to test whether a user has provided a non alphanumeric value. If they have, I want to return false. I'm pretty sure I am close, but I keep getting an error:
Complex object types cannot be converted to simple values.
I've tried multiple ways of making this work, but I can't get it to work.
Specifically, I want to allow only a through z and 0 through 9. No spaces, or special characters.
Can you help me tweak this?
<cfscript>
LOCAL.Description = trim(left(ARGUMENTS.Description, 15));
if (len(LOCAL.Description) lte 4) {
return false;
} else if (reMatchNoCase("[^A-Za-z0-9_]", LOCAL.Description) neq "") {
return false;
} else {
return true;
</cfscript>
W
reMatchNoCase returns Array which cannot be compared to the string, use ArrayLen() on the result in order to find out if there any matches
There is actually another problem in your code. First line will produce an error if the length of the description is less than 15, which means that the first IF is obsolete since it will always be false.
reMatchNoCase("[^A-Za-z0-9_]", LOCAL.Description) neq ""
It is because ReMatchNoCase returns an array, not a simple string. Either check the array length, or better yet, use ReFindNoCase instead. It returns the position of the first match, or 0 if it was not found.
You can also try the following approach:
<cfscript>
local.description = trim(local.description);
return reFind("(?i)^[A-Z0-9_]{5,}$", local.description)?true:false;
</cfscript>
I'm late to the party but reFindNoCase is the optimal solution in 2021. Here's how I would handle the code in the original question:
// best practice not to have a local var name identical to an argument var
var myValue = trim( left( arguments.description, 15 ) );
// return false if myValue is less than 4 or has special characters
return(
!len( myValue ) lte 4 &&
!reFindNoCase( "[^a-z0-9]", myValue )
);
So I've been actively programming bot in school and work the past 5 years, but I never tried to find out the difference between == and ===.
I can see the difference of a comparator using a single =, it'll look at the value of the left handed variable through the loop, ex:
while($line = getrow(something))
So what's the difference between == and === in statements such as:
if ($var1 === $var2)
//versus
if ($var1 == $var2)
Likewise:
if ($var1 !== $var2)
//versus
if ($var1 != $var2)
I have always used double equals, I have never used tripple.
The languages I use are :php, vb.net, java, javascript, c/c++.
I'm interested in learning systematically what is going on in a tripple quote that is different than that of a double quote.
When should one be used over another? Thanks for appeasing to my curiosity :)
Typically, == looks at equality of value only. So, for instance...
5 == 5.0 //true
However, === also considers value and type (in the languages I am familiar with).
var five = 5;
var five_float = (float)5.0;
five === 5; //true - both int, both equal to 5
five_float === 5; //false - both equal 5 but one is an int and one is a float
FYI, the = operator (usually called the assignment operator) is used to set the value of the left side parameter to the right side. This is pretty obvious. However, in most languages, this will also return true if the assignment is successful. You want to avoid using = where you mean to use == (or ===) because it will look like a comparison, but it's not - and it will return true unexpectedly.
For instance, lets say you want to check if a number is equal to 10...
myNumber = 7;
if(myNumber = 10)
{
//will always be true and execute this code because myNumber will successfully
//be assigned the value of 10 instead of checking to see if the number is 10.
//oops!
}
A final note - this is true in PHP and JavaScript. I don't think there is a === operator in C++ or Java and == has a slightly different meaning as well.
$a === $b TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
$a !== $b TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)
Reference
== will check the value only (equality operator), where === checks the data type as well (strict equality operator).
1 == '1' is true.
1 === '1' is false - the first is an Integer, the second is a String.
1 == true is true.
1 === true is false - the first is an Integer, the second is a Boolean.
Generally you want to use == (equality operator) but sometimes you want to make sure things are of certain types. I'm sure someone can provide an example, I can't think of one off the top of my head, but I've definitely used it.
In PHP and JavaScript (I'm not sure of other languages where the triple === syntax is valid) the difference is that === is a strict comparison. While == is loose. That means that === compares value and type, but == just compares value. A perfect example of this is the buggy PHP code below:
$str = 'Zebraman stole my child\'s pet lime!';
// Search for zebra man
if(strpos($str, 'Zebraman')){
echo 'The string contains "Zebraman"';
}else{
echo 'The string doesn\'t contain "Zebraman"';
}
Example Here
Since strpos($str, 'Zebraman') returns 0 (The index of the string Zebraman), and since 0 is falsy. That code will output The string doesn't contain "Zebraman". The correct code uses a strict comparison with false:
$str = 'Zebraman stole my child\'s pet lime!';
// Search for zebra man
if(strpos($str, 'Zebraman') !== false){
echo 'The string contains "Zebraman"';
}else{
echo 'The string doesn\'t contain "Zebraman"';
}
Example Here
See the PHP man page on strpos
I don't know if this holds true for all languages but in javascript the === stands for type comparison.
0 == false (true) 0 === false (false)
It is a common js error to not use the === when comparing a falsy value.
var a;
if(a) do something
(if a is zero the if will not get entered)
I am trying to pass value as 95%
numexu = 95%
"^((>|GT|>=|GE|<|LT|<=|LE|==|EQ|!=|NE)?\\s*\\d?[%]?)$
if (!regex.IsMatch(numexu))
throw new ArgumentException("Percent expression is in an invalid format.");
it is throwing exception in code.
Regards,
Regex
You are checking only for 1 number \\d?, try instead this: \\d{0,2}, this accepts 0, 1 or 2 numbers. The ? makes it 0 or 1 times matching.
I am not sure if you need to escape the %, if so then \\%. Additionally if you have only one character you can skip the brackets [%], so % (or \\%, if needed to escape)
This Function will work for your requirement
function check() {
var txtfield; txtfield =document.getElementById('txtbox').value;
var reg=/^(\d{0,2}%?$)/;
if(reg.test(txtfield)){
alert("match");
}
else { alert("Try again"); }
}