I need to validate a form that a user provides their name and a number. I have a regex that is supposed to make sure the name contains only letters and nothing else and also for the number input i need to make sure only numbers are in the field.
The code I have looks like
validator: (value) => value.isEmpty
? 'Enter Your Name'
: RegExp(
'!##<>?":_``~;[]\|=-+)(*&^%1234567890')
? 'Enter a Valid Name'
: null,
can i get a regex expression that validates a name in such a way if any special character or number is inputted it becomes wrong meaning only letters are valid and another that validates a number in such a way if an alphabetical letter or any special character is inputted it becomes wrong meaning only the input of a number is valid
Create a static final field for the RegExp to avoid creating a new instance every time a value is checked. Creating a RegExp is expensive.
static final RegExp nameRegExp = RegExp('[a-zA-Z]');
// or RegExp(r'\p{L}'); // see https://stackoverflow.com/questions/3617797/regex-to-match-only-letters
static final RegExp numberRegExp = RegExp(r'\d');
Then use it like
validator: (value) => value.isEmpty
? 'Enter Your Name'
: (nameRegExp.hasMatch(value)
? null
: 'Enter a Valid Name');
It seems to me you want
RegExp(r'[!##<>?":_`~;[\]\\|=+)(*&^%0-9-]').hasMatch(value)
Note that you need to use a raw string literal, put - at the end and escape ] and \ chars inside the resulting character class, then check if there is a match with .hasMatch(value). Notre also that [0123456789] is equal to [0-9].
As for the second pattern, you can remove the digit range from the regex (as you need to allow it) and add a \s pattern (\s matches any whitespace char) to disallow whitespace in the input:
RegExp(r'[!##<>?":_`~;[\]\\|=+)(*&^%\s-]').hasMatch(value)
Base on this answer and this information:
\p{L} or \p{Letter}: any kind of letter from any language.
Reference: http://www.regular-expressions.info/unicode.html
The regex for a name validation:
RegExp(r"^[\p{L} ,.'-]*$",
caseSensitive: false, unicode: true, dotAll: true)
.hasMatch(my_name)
Related
I want to restrict user from entering any special character in Input field apart from first character as + and total number of character not more than 15. I want to check it using regular expression on onChangeText in react native. If user another + then it should restrict it.
I am using below expression which accepts only numbers but now I want it to accept first character as +.
export default (val) => {
return val.replace(/\D+/g, '')
}
You may use
export default (val) => {
return val.replace(/^(\+)|\D/g, '$1')
}
See the regex demo and the regex graph:
The regex matches and captures into Group 1 a + at the start of the string or any non-digit char in all other contexts and the match is replaced with the contents of Group 1. So, if there is a + at the start, it will be put back into the resulting string, else, it will be removed from the string.
Using Alteryx, I have a field called Address which consists of fields like A32C, GH2X, ABC19E. So basically where digits are pinned between sets of letters. I am trying to use the RegEx tool to extract the digits out into a new column called ADDRESS1.
I have Address set to Field to Parse. Output method Parse.
My regular expression is typed in as:
(?:[[alpha]]+)(/d+)(?:[[alpha]]+)
And then I have (/d+) outputting to ADDRESS1. However, when I run this it parses 0 records. What am I doing wrong?
To match a digit, use [0-9] or \d. To match a letter, use [[:alpha:]].
Use
[[:alpha:]]+(\d+)[[:alpha:]]+
See the regex demo.
You can try this :
let regex = /(?!([A-Z]+))(\d+)(?=[A-Z]+)/g;
let values = 'A32CZ, GH2X, ABC19E'
let result = values.match(regex);
console.log(result);
I've built a password Generator:
Public Function PassGen()
Dim pool As String = "0123456789abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXYZ+#*#%&/()?!$-"
Dim rnd As New Random
Dim result As String
Dim i As Integer = 0
Do Until i = 10
result &= pool(rnd.Next(0, pool.Length))
i = i + 1
Loop
Return result
End Function
Now I'd like to check if the generated password contains a number, upper- and lowercase and special characters. If the generated password doesn't contain those 4 things, it should generate another password and check it again and so on.
I tried to loop a Regex.Match:
Dim text As String = PassGen()
Do Until Regex.Match(text, "^[0-9]$")
text = PassGen()
Loop
What didnt work as it wont let me loop a regex.match().
I also tried it with String.Contains(). But as far as I know the Contains-method can only check for one string and not for a range or a type(like Integer).
Is there a possibility to check my password for those four string-ranges or do I have to modify my function that it has to use one of each?
You could use the LIKE keyword in VB. The LIKE is like a mini-regex built in into VB.NET.
If text Like "*[A-Z]*" AndAlso text Like "*[a-z]*" AndAlso text Like "*[0-9]*" AndAlso text Like "*[+#*#%&/()?!$-]*" Then
' it is a valid password
Else
' password doesn't match required constraints... do whatever to regenerate it here...
End If
You can use one regex to check the password strength:
Do Until System.Text.RegularExpressions.Regex.IsMatch(text, "(?s)^(?=.*\d)(?=.*\p{Ll})(?=.*\p{Lu})(?=.*\W)")
The \W matches all special characters other than letters, digits and _, thus you have a much wider scope with it than manually defining a character class like [+#*#%&/()?!$-].
The (?s) is an inline singleline modifier to force . to match a newline, too. The \d matches a digit, the \p{Ll} matches a lowercase letter, and \p{Lu} matches an uppercase letter. The lookaheads (?=...) are executed one after another upon success. If one of them returns false, the whole match is failed.
I want to create a url friendly string (one that will only contain letters, numbers and hyphens) from a user input to :
remove all characters which are not a-z, 0-9, space or hyphens
replace all spaces with hyphens
replace multiple hyphens with a single hyphen
Expected outputs :
my project -> my-project
test project -> test-project
this is # long str!ng with spaces and symbo!s -> this-is-long-strng-with-spaces-and-symbos
Currently i'm doing this in 3 steps :
$identifier = preg_replace('/[^a-zA-Z0-9\-\s]+/','',strtolower($project_name)); // remove all characters which are not a-z, 0-9, space or hyphens
$identifier = preg_replace('/(\s)+/','-',strtolower($identifier)); // replace all spaces with hyphens
$identifier = preg_replace('/(\-)+/','-',strtolower($identifier)); // replace all hyphens with single hyphen
Is there a way to do this with one single regex ?
Yeah, #Jerry is correct in saying that you can't do this in one replacement as you are trying to replace a particular string with two different items (a space or dash, depending on context). I think Jerry's answer is the best way to go about this, but something else you can do is use preg_replace_callback. This allows you to evaluate an expression and act on it according to what the match was.
$string = 'my project
test project
this is # long str!ng with spaces and symbo!s';
$string = preg_replace_callback('/([^A-Z0-9]+|\s+|-+)/i', function($m){$a = '';if(preg_match('/(\s+|-+)/i', $m[1])){$a = '-';}return $a;}, $string);
print $string;
Here is what this means:
/([^A-Z0-9]+|\s+|-+)/i This looks for any one of your three quantifiers (anything that is not a number or letter, more than one space, more than one hyphen) and if it matches any of them, it passes it along to the function for evaluation.
function($m){ ... } This is the function that will evaluate the matches. $m will hold the matches that it found.
$a = ''; Set a default of an empty string for the replacement
if(preg_match('/(\s+|-+)/i', $m[1])){$a = '-';} If our match (the value stored in $m[1]) contains multiple spaces or hyphens, then set $a to a dash instead of an empty string.
return $a; Since this is a function, we will return the value and that value will be plopped into the string wherever it found a match.
Here is a working demo
I don't think there's one way of doing that, but you could reduce the number of replaces and in an extreme case, use a one liner like that:
$text=preg_replace("/[\s-]+/",'-',preg_replace("/[^a-zA-Z0-9\s-]+/",'',$text));
It first removes all non-alphanumeric/space/dash with nothing, then replaces all spaces and multiple dashes with a single one.
Since you want to replace each thing with something different, you will have to do this in multiple iterations.
Sorry D:
Need help building a VBScript regex that checks for a valid computer name and returns only invalid characters. String can contain numbers, upper and lower case letters, and (-) sign only. It can't start or end with (-) and cannot be only numbers.
Valid (Returns no match):
computer
Computer8
8Computer
Com8puter
Com-Puter
Computer-123
Invalid (Returns a match to invalid characters):
123
-computer
computer-
com*puter
PC&123
According to this: http://msdn.microsoft.com/en-us/library/ms974570.aspx VBScript has its own regex syntactic flavour. Note that NetBIOS computer names have a length limit of 15.
Then it should be "^\w[\w-]{0,14}$"
That RegEx satisfies all of the requirements except the "is all numbers". That can be done by running a second regex "^\d+$".
In code:
Dim regexValid, regexNumber
Set regexValid = New RegExp
Set regexNumber = New RegExp
regexValid.Global = True
regexValid.IgnoreCase = True
regexNumber.Global = True
regexNumber.IgnoreCase = True
regexValid.Pattern = "^\w[\w\-]{0,14}$"
regexNumber.Pattern = "^\d+$"
Dim inputString
inputString = InputBox("Computer name?")
If regexValid.Test( inputString ) And Not regexNumber.Test( inputString ) Then
' It's a valid computer name string
Else
' It's invalid
End If
Hmm, this is the first VBScript I've written this year.
I ended up switching the valid and invalid returns. I also ended up using two different RegEx strings. The first is:
^[0-9a-zA-Z]{1,}[-]*[0-9a-zA-Z]{1,}$
This doesn't allow the (-) at the beginning or end and requires all numbers, letters, or (-). It also requires a string of at least two characters.
The second is:
"[a-zA-Z]"
This makes sure there is at least one letter included.
Something like this /^([0-9]|[a-zA-Z]){1,}[a-zA-Z0-9-]+([0-9]|[a-zA-Z]){1,}$/