Regular expression not working with \ and ] - regex

I have a regex for validating a password which has to be at least 8 chars and must contain letter(upper and lower case) number and a special character from set ^ $ * . [ ] { } ( ) ? - " ! # # % & / \ , > < ' : ; | _ ~ ` .
I face 2 problems, after adding the / to the reg exp its not recognized (other characters are still working OK. If I add the /] as well the expression no longer works (everything is invalid though the pattern seems to be ok in the browser debug mode).
The regex string
static get PASSWORD_VALIDATION_REGEX(): string {
return '(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])' + // contains lowercase number uppercase
'(?=.*[\-~\$#!%#<>\|\`\\\/\[;:=\+\{\}\.\(\)*^\?&\"\,\'])' + // special
'.{8,}'; // more than allowed char
}
I used the regexp as a form validator and as a match in function
password: ['', {validators: [Validators.required,
Validators.pattern(StringUtils.PASSWORD_VALIDATION_REGEX)
],
updateOn: 'change'
}
]
//....
value.match(StringUtils.PASSWORD_VALIDATION_REGEX)
Tried to use only (?=.*[\\]) for the special chars list, in that case I've received a console error
Invalid regular expression: /^(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])(?=.*[\]).{8,}$/: Unterminated character class
For '(?=.*[\]])' no console error but the following error is present in the form validation 'pattern'
actualValue: "AsasassasaX000[[][]"
requiredPattern: "^(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])(?=.*[]]).{8,}$"
The same value and pattern fails on https://regex101.com/
Thanks for your help / suggestions in advance!

You have overescaped your pattern and failed to escape the ] char correctly. In JavaScript regex, ] inside a character class must be escaped.
If you are confused with how to define escapes inside a string literal (and it is rather confusing indeed), you should use a regex literal. One thing to remember about the regex use with Validators.pattern is that the string pattern is anchored by the Angular framework by enclosing the whole pattern with ^ and $, so these anchors must be present when you define the pattern as a regex literal.
Use
static get PASSWORD_VALIDATION_REGEX(): string {
return /^(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])(?=.*[-~$#!%#<>|`\\\/[\];:=+{}.()*^?&",']).{8,}$/;
}
Note the \] that matches a ] char and \\ to match \ inside [...].

Related

Regex to evaluate phone number in Pentaho [duplicate]

I wanted to remove the special characters like ! # # $ % ^ * _ = + | \ } { [ ] : ; < > ? / in a string field.
I used the "Replace in String" step and enabled the use RegEx. However, I do not know the right syntax that I will put in "Search" to remove all these characters from the string. If I only put one character in the "Search" it was removed from the string. How can I remove all of these??
This is the picture of how I did it:
As per documentation, the regex flavor is Java. You may use
\p{Punct}
See the Java regex syntax reference:
\p{Punct} Punctuation: One of !"#$%&'()*+,-./:;<=>?#[]^_`{|}~

WPF Regex special character '&' incorrect syntax

In my WPF application I want to validate email with this conditions.
The local part can be up to 64 characters in length and consist of any combination of alphabetic characters, digits, or any of the following special characters: ! # $ % & ‘ * + – / = ? ^ _ ` . { | } ~.
My Regex is
[a-zA-Z0-9!#$%'*+–=?^_`.{|}~/&]{1,64}#[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}
But when i use '&' character it shows the following error
Expected the following token: ";".
I have found my solution.
I had to use &
and
My final Regex is
[^.][a-zA-Z0-9!#$%'*+=?^_`.{|}~-/&]{1,64}#[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}

Remove special characters using Pentaho - Replace in String

I wanted to remove the special characters like ! # # $ % ^ * _ = + | \ } { [ ] : ; < > ? / in a string field.
I used the "Replace in String" step and enabled the use RegEx. However, I do not know the right syntax that I will put in "Search" to remove all these characters from the string. If I only put one character in the "Search" it was removed from the string. How can I remove all of these??
This is the picture of how I did it:
As per documentation, the regex flavor is Java. You may use
\p{Punct}
See the Java regex syntax reference:
\p{Punct} Punctuation: One of !"#$%&'()*+,-./:;<=>?#[]^_`{|}~

Fix the regular expression

I need help with writing a regular expression for a string that should contain alphanumeric signs and only one of these: #,?,$,%
for example: abx12A#we is ok but fsa?#ds is not ok
I tried with something like /[a-zA-z0-9][#?$%]{0,1}/ but its not working.
Any ideas?
Thanks
Something like:
^[a-zA-Z0-9]*[#?$%]?[a-zA-Z0-9]*$
should do the trick (and, depending on your regex engine, you may need to escape one or more of those special characters).
It's basically zero or more from the "alpha"-type class, followed by zero or one from the "special"-type class, followed once again by zero or more "alpha".
You can adjust what's contained in each character class as you see fit, but this is the general way to get one of something within a sea of other things.
If you need to match an empty string, too, you need to use
^[a-zA-Z0-9]*(?:[#?$%][a-zA-Z0-9]*)?$
See the regex demo
Details:
^ - start of string
[a-zA-Z0-9]* - zero or more alphanumeric
(?:[#?$%][a-zA-Z0-9]*)? - exactly 1 occurrence of:
[#?$%] - a char from the set
[a-zA-Z0-9]* - zero or more alphanumeric
$ - end of string
NOTE: [A-z] is a common typo resulting in serious issues.
If you do not want to allow an empty string, replace * with +:
^[a-zA-Z0-9]+(?:[#?$%][a-zA-Z0-9]+)?$
^ ^
try this
const regex = /^[a-zA-z0-9]*[#?$%]?[a-zA-z0-9]*$/
const perfectInputs = [
'abx12A#we',
'a#',
'#a',
'a#a'
]
const failedInputs = [
'fsa?#ds'
]
console.log('=========== test should be success ============')
for (const perfectInput of perfectInputs) {
const result = regex.test(perfectInput)
console.log(`test ${perfectInput}: ${result}`)
console.log()
}
console.log('=========== test should be failed ============')
for (const failedInput of failedInputs) {
const result = regex.test(failedInput)
console.log(`test ${failedInput}: ${result}`)
console.log()
}
If the special character can be at the begining or at the end of the string, you could use lookahead:
^(?=[^#?$%]*[#?$%]?[^#?$%]*$)[a-zA-Z0-9#?$%]+$
/^(?=[^#?$%]*[#?$%]?[^#?$%]*$)[a-zA-Z0-9#?$%]*$/
\__________^^^^^^^_________/ -------------------- not more than once
\_____________/ ----- other conditions

RegEx for including alphanumeric and special characters

I have requirement to allow alphanumeric and certain other characters for a field. I am using this regular expression:
"^[a-zA-Z0-9!##$&()-`.+,/\"]*$".
The allowed special characters are! # # $ & ( ) - ‘ . / + , “
But when I test the pattern with a string "test_for_extended_alphanumeric" , the string passes the test. I don't have "_" allowed in the pattern. What am I doing wrong?
You need to escape the hyphen:
"^[a-zA-Z0-9!##$&()\\-`.+,/\"]*$"
If you don't escape it then it means a range of characters, like a-z.
In your character class the )-' is interpreted as a range in the same way as e.g. a-z, it therefore refers to any character with a decimal ASCII code from 41 ) to 96 '.
Since _ has code 95, it is within the range and therefore allowed, as are <, =, > etc.
To avoid this you can either escape the -, i.e. \-, or put the - at either the start or end of the character class:
/^[a-zA-Z0-9!##$&()`.+,/"-]*$/
There is no need to escape the ", and note that because you are using the * quantifier, an empty string will also pass the test.
Using this regex you allow all alphanumeric and special characters. Here \w is allowing all digits and \s allowing space
[><?#+'`~^%&\*\[\]\{\}.!#|\\\"$';,:;=/\(\),\-\w\s+]*
The allowed special characters are ! # # $ & ( ) - ‘ . / + , “ = { } [ ] ? / \ |
Hyphens in character classes denote a range unless they are escaped or at the start or end of the character class. If you want to include hyphens, it's typically a good idea to put them at the front so you don't even have to worry about escaping:
^[-a-zA-Z0-9!##$&()`.+,/\"]*$
By the way, _ does indeed fall between ) and the backtick in ASCII:
http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
How about this.. which allows special characters and as well as alpha numeric
"[-~]*$"
Because I don't know how many special characters exist, it is difficult to check the string contains special character by white list. It may be more efficient to check the string contains only alphabet or numbers.
for kotlin example
fun String.hasOnlyAlphabetOrNumber(): Boolean {
val p = Pattern.compile("[^a-zA-Z0-9]")
return !(p.matcher(this).matches())
}
for swift4
func hasOnlyAlphabetOrNumber() -> Bool {
if self.isEmpty { return false }
do {
let pattern = "[^a-zA-Z0-9]"
let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
return regex.matches(in: self, options: [], range: NSRange(location: 0, length: self.count)).count == 0
} catch {
return false
}
}
Regex sucks. Here is mine
/^[a-zA-Z\d-!##$%^&._"'()+,/;<>=|?[]\`~{}]$/
Mine is a little different than others but it is more self explanatory. You use \ in front of any special symbol like ] or . I had issues with -, , and ] so I had to put ], \, and move the - to the left. I also had issues with | but I moved it left and it fixed it.