Why does this regex unit test fail?
200
Take a look at the regex101: https://regex101.com/r/AmJ0Rv/1
Your regex matches the T
in TEST @NAME
, so that means the issue isn't with the code but with your regex, if the expected answer isn't true
Try using this:
^[-A-Z `’.\' '`]+
and checking if the result is the same as the original string.
Alternatively, you can use this regex:
[^-A-Z `’.\' '`]
If there is a match, then you should return false
and if there isn't you should return true
. What this regex does is check if there is any characters that aren't allowed.
Author by
Rutger Huijsmans
Updated on December 13, 2022Comments
-
Rutger Huijsmans 11 months
I'm writing an app using Dart / Flutter.
I've written this regex function to check certain strings:
static final String nameOnCardRegex = r'^[\-A-Z `’\.\' '`]'; static final int nameOnCardMaxLength = 21; static bool checkNameOnCard(String nameOnCardInput) { if (nameOnCardInput == null || nameOnCardInput.length > nameOnCardMaxLength) { return false; } return RegExp(nameOnCardRegex).hasMatch(nameOnCardInput); }
I'm trying to unit test it with this function:
test("[Name On Card String Validator] Check invalid Name On Card input 2", () async { expect(YouStrings.checkNameOnCard("TEST @NAME"), false); });
I expect this function to return false (because i'm passing in a
@
character). It however returns true.Test results:
package:test_api expect test/data/string_validator_module_test.dart 151:9 checkNameOnCardTest.<fn> ===== asynchronous gap =========================== dart:async _AsyncAwaitCompleter.completeError test/data/string_validator_module_test.dart checkNameOnCardTest.<fn> Expected: <false> Actual: <true>
-
Rutger Huijsmans about 4 yearsThanks for the link and info. That is very helpful. Your suggested regex still matches true when i don't expect it to though. I'm expecting it to return false when there is any character in the string that isn't in the regex.
-
Sheshank S. about 4 years@RutgerHuijsmans I know. You have to get the string match of it and see if it is the same string as the input string.
-
Rutger Huijsmans about 4 yearsReally? Is there no way to return just true or false using regex without doing that?
-
Sheshank S. about 4 years@RutgerHuijsmans Well, actually I'll update my answer in a second
-
Rutger Huijsmans about 4 yearsThanks! I removed them
-
Sheshank S. about 4 years@CasimiretHippolyte I've removed them from my answer as well