Reg expression validate / \ # & characters - regex

I've been learning how Regular expressions work, which is very tricky for me. I would like to validate this chars below from input field. Basically if string contains any of these characters, alert('bad chars')
/
\
#
&
I found this code, but when I change it around doesn't seem to work. How can I alter this code to meet my needs?
var str = $(this).val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
alert('bad');
return false;
} else {
alert('good');
}

/^[a-zA-Z0-9- ]*$/ means the following:
^ the string MUST start here
[a-zA-Z0-9- ] a letter between a and z upper or lower case, a number between 0 and 9, dashes (-) and spaces.
* repeated 0 or more times
$ the string must end here.
In the case of "any character but" you can use ^ like so: /^[^\/\\#&]*$/. If this matches true, then it doesn't have any of those characters. ^ right after a [ means match anything that isn't the following.
.

You could just try the following:
if("/[\\/#&]/".test(str) == true) {
alert('bad');
return false;
} else {
alert('good');
}
NOTE: I'm not 100% on what characters need to be escaped in JavaScript vs. .NET regular expressions, but basically, I'm saying if your string contains any of the characters \, /, # or &, then alert 'bad'.

Related

regex - how to specify the expressions to exclude

I need to replace two characters {, } with {\n, \n}.
But they must be not surrounded in '' or "".
I tried this code to achieve that
text = 'hello(){imagine{myString("HELLO, {WORLD}!")}}'
replaced = re.sub(r'{', "{\n", text)
Ellipsis...
Naturally, This code replaces curly brackets that are surrounded in quote marks.
What are the negative statements like ! or not that can be used in regular expressions?
And the following is what I wanted.
hello(){
imagine{
puts("{HELLO}")
}
}
In a nutshell - what I want to do is
Search { and }.
If that is not enclosed in '' or ""
replace { or } to {\n or \n}
In the opposite case, I can solve it with (?P<a>\".*){(?P<b>.*?\").
But I have no clue how I can solve it in my case.
First replace all { characters with {\n. You will also be replacing {" with {\n". Now, you can replace back all {\n" characters with {".
text = 'hello(){imagine{puts("{HELLO}")}}'
replaced = text.replace('{', '{\n').replace('{\n"','{"')
You may match single and double quoted (C-style) string literals (those that support escape entities with backslashes) and then match { and } in any other context that you may replace with your desired values.
See Python demo:
import re
text = 'hello(){imagine{puts("{HELLO}")}}'
dblq = r'(?<!\\)(?:\\{2})*"[^"\\]*(?:\\.[^"\\]*)*"'
snlq = r"(?<!\\)(?:\\{2})*'[^'\\]*(?:\\.[^'\\]*)*'"
rx = re.compile(r'({}|{})|[{{}}]'.format(dblq, snlq))
print(rx.pattern)
def repl(m):
if m.group(1):
return m.group(1)
elif m.group() == '{':
return '{\n'
else:
return '\n}'
# Examples
print(rx.sub(repl, text))
print(rx.sub(repl, r'hello(){imagine{puts("Nice, Mr. \"Know-all\"")}}'))
print(rx.sub(repl, "hello(){imagine{puts('MORE {HELLO} HERE ')}}"))
The pattern that is generated in the code above is
((?<!\\)(?:\\{2})*"[^"\\]*(?:\\.[^"\\]*)*"|(?<!\\)(?:\\{2})*'[^'\\]*(?:\\.[^'\\]*)*')|[{}]
It can actually be reduced to
(?<!\\)((?:\\{2})*(?:"[^"\\]*(?:\\.[^"\\]*)*"|'[^'\\]*(?:\\.[^'\\]*)*'))|[{}]
See the regex demo.
Details:
The pattern matches 2 main alternatives. The first one matches single- and double-quoted string literals.
(?<!\\) - no \ immediately to the left is allowed
((?:\\{2})*(?:"[^"\\]*(?:\\.[^"\\]*)*"|'[^'\\]*(?:\\.[^'\\]*)*')) - Group 1:
(?:\\{2})* - 0+ repetitions of two consecutive backslashes
(?: - a non-capturing group:
"[^"\\]*(?:\\.[^"\\]*)*" - a double quoted string literal
| - or
'[^'\\]*(?:\\.[^'\\]*)*' - a single quoted string literal
) - end of the non-capturing group
| - or
[{}] - a { or }.
In the repl method, Group 1 is checked for a match. If it matched, the single- or double-quoted string literal is matched, it must be put back where it was. Else, if the match value is {, it is replaced with {\n, else, with \n}.
Replace { with {\n:
text.replace('{', '{\n')
Replace } with \n}:
text.replace('}', '\n}')
Now to fix the braces that were quoted:
text.replace('"{\n','"{')
and
text.replace('\n}"', '}"')
Combined together:
replaced = text.replace('{', '{\n').replace('}', '\n}').replace('"{\n','"{').replace('\n}"', '}"')
Output
hello(){
imagine{
puts("{HELLO}")
}
}
You can check the similarities with the input and try to match them.
text = 'hello(){imagine{puts("{HELLO}")}}'
replaced = text.replace('){', '){\n').replace('{puts', '{\nputs').replace('}}', '\n}\n}')
print(replaced)
output:
hello(){
imagine{
puts("{HELLO}")
}
}
UPDATE
try this: https://regex101.com/r/DBgkrb/1

How to make regexp for multiple condition?

I have regexp code like below (I'm using VerbalExpression dart plugin ), My purpose is to check that a string starts with "36", followed by "01", "02", or "03". After that can be anything as long as the whole string is 16 characters long.
var regex = VerbalExpression()
..startOfLine()
..then("36")
..then("01")
..or("02")
..anythingBut(" ")
..endOfLine();
String nik1 = "3601999999999999";
String nik2 = "3602999999999999";
String nik3 = "3603999999999999";
print('result : ${regex.hasMatch(nik1)}');
print('Hasil : ${regex.hasMatch(nik2)}');
print('Hasil : ${regex.hasMatch(nik3)}');
my code only true for nik1 and nik2, however i want true for nik3, I noticed that i can't put or() after or() for multiple check, it just give me all false result, how do i achieve that?
I'm not familiar with VerbalExpression, but a RegExp that does this is straightforward enough.
const pattern = r'^36(01|02|03)\S{12}$';
void main() {
final regex = RegExp(pattern);
print(regex.hasMatch('3601999999999999')); // true
print(regex.hasMatch('3602999999999999')); // true
print(regex.hasMatch('3603999999999999')); // true
print(regex.hasMatch('360199999999999')); // false
print(regex.hasMatch('3600999999999999')); // false
print(regex.hasMatch('36019999999999999')); // false
}
Pattern explanation:
The r prefix means dart will interpret it as a raw string ("$" and "\" are not treated as special).
The ^ and $ represent the beginning and end of the string, so it will only match the whole string and cannot find matches from just part of the string.
(01|02|03) "01" or "02" or "03". | means OR. Wrapping it in parentheses lets it know where to stop the OR.
\S matches any non-whitespace character.
{12} means the previous thing must be repeated 12 times, so \S{12} means any 12 non-whitespace characters.

c# Regex expression to extract all non-numeric values in brackets

This is the Regex expression i have built so far \{([^{]*[^0-9])\}.
"This is the sample string {0} {1} {} {abc} {12abc} {abc123}"
I wish to extract everything within the string that includes brackets and that does not contain only an integer.
(e.g) '{}'
'{abc}' '{12abc}' '{abc123}'
However the last one which contains numbers at the end is not extracted with the rest.
{abc123}
How can i extract all values in the string that are in curly brackets and do not contain an Integer?
You may use
var res = Regex.Matches(s, #"{(?!\d+})[^{}]*}")
.Cast<Match>()
.Select(x => x.Value)
.ToList();
See the regex demo and the online C# demo.
Pattern details
{ - a { char
(?!\d+}) - no 1+ digits and then } allowed immediately to the right of the current location
[^{}]* - 0+ chars other than { and }
} - a } char.

regular expression which should allow limited special characters

Can any one tell me the regular expression for textfield which should not allow following characters and can accept other special characters,alphabets,numbers and so on :
+ - && || ! ( ) { } [ ] ^ " ~ * ? : \ # &
this will not allow string that contains any of the characters in any part of the string mentioned above.
^(?!.*[+\-&|!(){}[\]^"~*?:#&]+).*$
See Here
Brief Explanation
Assert position at the beginning of a line (at beginning of the string or after a line break character) ^
Assert that it is impossible to match the regex below starting at this position (negative lookahead) (?!.*[+\-&|!(){}[\]^"~*?:#&]+)
Match any single character that is not a line break character .*
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) *
Match a single character present in the list below [+\-&|!(){}[\]^"~*?:#&]+
Between one and unlimited times, as many times as possible, giving back as needed (greedy) +
The character "+" +
A "-" character \-
One of the characters &|!(){}[” «&|!(){}[
A "]" character \]
One of the characters ^"~*?:#&” «^"~*?:#&
Match any single character that is not a line break character .*
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) *
Assert position at the end of a line (at the end of the string or before a line break character) $
Its usually better to whitelist characters you allow, rather than to blacklist characters you don't allow. both from a security standpoint, and from an ease of implementation standpoint.
If you do go down the blacklist route, here is an example, but be warned, the syntax is not simple.
http://groups.google.com/group/regex/browse_thread/thread/0795c1b958561a07
If you want to whitelist all the accent characters, perhaps using unicode ranges would help? Check out this link.
http://www.regular-expressions.info/unicode.html
I recognize those as the characters which need to be escaped for Solr. If this is the case, and if you are coding in PHP, then you should use my PHP utility functions from Github. Here is one of the Solr functions from there:
/**
* Escape values destined for Solr
*
* #author Dotan Cohen
* #version 2013-05-30
*
* #param value to be escaped. Valid data types: string, array, int, float, bool
* #return Escaped string, NULL on invalid input
*/
function solr_escape($str)
{
if ( is_array($str) ) {
foreach ( $str as &$s ) {
$s = solr_escape($s);
}
return $str;
}
if ( is_int($str) || is_float($str) || is_bool($str) ) {
return $str;
}
if ( !is_string($str) ) {
return NULL;
}
$str = addcslashes($str, "+-!(){}[]^\"~*?:\\");
$str = str_replace("&&", "\\&&", $str);
$str = str_replace("||", "\\||", $str);
return $str;
}

Regex to validate passwords with characters restrictions

I need to validate a password with these rules:
6 to 20 characters
Must contain at least one digit;
Must contain at least one letter (case insensitive);
Can contain the following characters: ! # # $ % & *
The following expression matches all but the last requirement. What can I do with the last one?
((?=.*\d)(?=.*[A-z]).{6,20})
I'm not completely sure I have this right, but since your last requirement is "Can contain the following characters: !##$%&*" I am assuming that other special characters are not allowed. In other words, the only allowed characters are letters, digits, and the special characters !##$%&*.
If this is the correct interpretation, the following regex should work:
^((?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9!##$%&*]{6,20})$
Note that I changed your character class [A-z] to [a-zA-Z], because [A-z] will also include the following characters: [\]^_`
I also added beginning and end of string anchors to make sure you don't get a partial match.
^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9!##$%&*]{6,20}$
Regex could be:-
^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9!##$%&*]{6,20}$
How about this in Javascript:-
function checkPwd(str) {
if (str.length < 6) {
return("too_short");
} else if (str.length > 20) {
return("too_long");
} else if (str.search(/\d/) == -1) {
return("no_num");
} else if (str.search(/[a-zA-Z]/) == -1) {
return("no_letter");
} else if (str.search(/[^a-zA-Z0-9\!\#\#\$\%\^\&\*\(\)\_\+]/) != -1) {
return("bad_char");
}
return("ok");
}
Also check out this