I use regex validation in my custom textfield listener, to check if password valid
this is my validation code
RegExp regexUpper = RegExp(r'^(?=.*[A-Z])$');
RegExp regexLower = RegExp(r'^(?=.*[a-z])$');
RegExp regexLength = RegExp(r'^.{8,}$');
if (!regexLength.hasMatch(value.toString())) {
return 'Пароль слишком короткий';
}
if (!regexLower.hasMatch(value.toString())) {
print(value);
return 'Пароль должен содержать хотя бы одну маленькую букву';
}
if (!regexUpper.hasMatch(value.toString())) {
return 'Введите хотя бы одну заглавную букву';
}
return null;
regexLength work correctly but other not.
What i did wrong and how i can fix it ?
You should not use lookarounds wrapped with anchors.
You can fix the issues with
RegExp regexUpper = RegExp(r'[A-Z]');
RegExp regexLower = RegExp(r'[a-z]');
RegExp regexLength = RegExp(r'^.{8,}$');
Look: ^(?=.*[A-Z])$ asserts the current position at the start of string (^), then checks if there is an uppercase ASCII letter ([A-Z]) anywhere after zero or more chars other than line break chars (as many as possible, with .*), and then requires the end of string ($) (right at the start of string). This is an example of a pattern that never matches any string.
Related
i am new to scala and hate regex :D
cuurently i am debuggig a piece of code
def validateReslutions(reslutions: String): Unit = {
val regex = "(\\d+-\\d+[d,w,m,h,y],?)*"
if (!reslutions.matches(regex)) {
throw new Error("no match")
} else {
print("matched")
}
}
validateReslutions(reslutions = "(20-1w,100-1w)")
}
the problem is it produces no match for this input , so how to correct the regex to match this input
Your (20-1w,100-1w) string contains a pair of parentheses at the start and end, and the rest matches with your (\d+-\d+[d,w,m,h,y],?)* regex. Since String#matches requires a full string match, you get an exception.
Include the parentheses patterns to the regex to avoid the exception:
def validateReslutions(reslutions: String): Unit = {
val regex = """\((\d+-\d+[dwmhy],?)*\)"""
if (!reslutions.matches(regex)) {
throw new Error("no match")
} else {
print("matched")
}
}
validateReslutions(reslutions = "(20-1w,100-1w)")
// => matched
See the Scala demo.
Note the triple quotes used to define the string literal, inside which you can use single backslashes to define literal backslash chars.
Also, mind the absence of commas in the character class, they match literal commas in the text, they do not mean "or" inside character classes.
I have a scenario where i want to extract some substring based on following condition.
search for any pattern myvalue=123& , extract myvalue=123
If the "myvalue" present at end of the line without "&", extract myvalue=123
for ex:
The string is abcdmyvalue=123&xyz => the it should return myvalue=123
The string is abcdmyvalue=123 => the it should return myvalue=123
for first scenario it is working for me with following regex - myvalue=(.?(?=[&,""]))
I am looking for how to modify this regex to include my second scenario as well. I am using https://regex101.com/ to test this.
Thanks in Advace!
Some notes about the pattern that you tried
if you want to only match, you can omit the capture group
e* matches 0+ times an e char
the part .*?(?=[&,""]) matches as least chars until it can assert eiter & , or " to the right, so the positive lookahead expects a single char to the right to be present
You could shorten the pattern to a match only, using a negated character class that matches 0+ times any character except a whitespace char or &
myvalue=[^&\s]*
Regex demo
function regex(data) {
var test = data.match(/=(.*)&/);
if (test === null) {
return data.split('=')[1]
} else {
return test[1]
}
}
console.log(regex('abcdmyvalue=123&3e')); //123
console.log(regex('abcdmyvalue=123')); //123
here is your working code if there is no & at end of string it will have null and will go else block there we can simply split the string and get the value, If & is present at the end of string then regex will simply extract the value between = and &
if you want to use existing regex then you can do it like that
var test = data1.match(/=(.*)&|=(.*)/)
const result = test[1] ? test[1] : test[2];
console.log(result);
function getPrecedents(thisFormula){
var exp = /(\w+\!)?\$?[A-Z]{1,}(?:\d+)?(\:?\$?\w+)*(?!\()\b/gm;
var results=[];
var result;
while ((result=exp.exec(thisFormula))!== null){
results.push(result);
}
return results;
}
From the above code I am getting the following results
Trigger_Hires!$AA$15
AD$7
Trigger_Hires!$AC60
Trigger_Hires!$AB60
Rev
Import_Staffing!AD$16
Trigger_Hires!$AC60
Trigger_Hires!$AB60
Customers
Import_Staffing!AD$19
Trigger_Hires!$AC60
I would like to eliminate results that are just letters like Rev and Customers either with modified regexp or 2nd loop
I suggest adding a check before adding the match to the results array:
while (result=exp.exec(thisFormula)) {
if (!/^[A-Za-z]+$/.test(result[0]))
results.push(result[0]);
}
Note you need to access result[0] to get the whole regex match value. To check if the match value is all letters, ^[A-Za-z]+$ regex is used: ^ asserts the position at the start of the string, [A-Za-z]+ matches 1+ letters and $ asserts the position at the end of the string.
I have reactive form and one of the controls should be validated with the pattern .*[^\s].*. In case it is used in template-driven forms, it works well. But in a case of reactive - does not. What should I change to fix it?
this._form = this._formBuilder.group({
description: ['', [Validators.required, Validators.pattern('.*[^\S].*')]]
}
Have a look at the Validator.js:
/**
* Validator that requires a control to match a regex to its value.
*/
static pattern(pattern: string|RegExp): ValidatorFn {
if (!pattern) return Validators.nullValidator;
let regex: RegExp;
let regexStr: string;
if (typeof pattern === 'string') {
regexStr = `^${pattern}$`;
regex = new RegExp(regexStr);
} else {
regexStr = pattern.toString();
regex = pattern;
}
return (control: AbstractControl): {[key: string]: any} => {
if (isEmptyInputValue(control.value)) {
return null; // don't validate empty values to allow optional controls
}
const value: string = control.value;
return regex.test(value) ? null :
{'pattern': {'requiredPattern': regexStr, 'actualValue': value}};
};
}
The point is that the regex pattern is passed either like a regex literal, or as a string literal. When you pass it as a regex literal, you may use
/\S*\s.*/
It will be "converted" to a string with pattern.toString() and ^ and $ will be added - "^\\S*\\s.*$". This is exactly a string pattern you may pass in the Validators.Pattern, too.
Note that ^\S*\s.*$ will match a string that starts with 0+ non-whitespace chars, then has 1 obligatory whitespace, and then has any 0+ chars other than line break chars. It is a bit faster than /^.*\s.*$/. Note that \s = [^\S].
I am parsing a feed and need to exclude fields that consist of a string with the word "bad", in any combination of case.
For example "bad" or "Bad id" or "user has bAd id" would not pass the regular expression test,
but "xxx Badlands ddd" or "aaabad" would pass.
Exclude anything that matches /\bbad\b/i
The \b matches word boundaries and the i modifier makes it case insensitive.
For javascript, you can just put your word in the regex and do the match \b stnads for boundries, which means no character connected :
/\bbad\b/i.test("Badkamer") // i for case-insensitive
You may try this regex:
^(.*?(\bbad\b)[^$]*)$
REGEX DEMO
I think the easiest way to do this would be to split the string into words, then check each word for a match, It could be done with a function like this:
private bool containsWord(string searchstring, string matchstring)
{
bool hasWord = false;
string[] words = searchstring.split(new Char[] { ' ' });
foreach (string word in words)
{
if (word.ToLower() == matchstring.ToLower())
hasWord = true;
}
return hasWord;
}
The code converts everything to lowercase to ignore any case mismatches. I think you can also use RegEx for this:
static bool ExactMatch(string input, string match)
{
return Regex.IsMatch(input.ToLower(), string.Format(#"\b{0}\b", Regex.Escape(match.ToLower())));
}
\b is a word boundary character, as I understand it.
These examples are in C#. You didn't specify the language