RegEx pattern test is failing in javascript - javascript

I have below RegEx to validate a string..
var str = "Thebestthingsinlifearefree";
var patt = /[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?#\[\]^_`{|}~]*/g;
var res = patt.test(str);
the result will always give true but I thought it would give false.. because I checking any pattern which is not in the patt variable...
The given string is valid and it contains only Alphabets with capital and small case letters. Not sure what is wrong with the pattern.

Here's your code:
var str = "Thebestthingsinlifearefree";
var patt = /[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?#\[\]^_`{|}~]*/g;
console.log(patt.test(str));
The regex
/[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?#\[\]^_`{|}~]*/g
will match anything since it accepts match of length 0 due to the quantifier *.
Just add anchors:
var str = "Thebestthingsinlifearefree";
var patt = /^[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?#\[\]^_`{|}~]*$/;
console.log(patt.test(str));
Here's an explanation or your regex:
[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?#\[\]^_`{|}~]* match a single character not present in the list below
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
0-9 a single character in the range between 0 and 9
A-Z a single character in the range between A and Z (case sensitive)
a-z a single character in the range between a and z (case sensitive)
! a single character in the list ! literally
\\ matches the character \ literally
#$%&()*+, a single character in the list #$%&()*+, literally (case sensitive)
\- matches the character - literally
. the literal character .
\/ matches the character / literally
:;<=>?# a single character in the list :;<=>?# literally (case sensitive)
\[ matches the character [ literally
\] matches the character ] literally
^_`{|}~ a single character in the list ^_`{|}~ literally

Note that:
A search for a missing pattern is better expressed by a negative condition in code (!patt.test...).
You need to escape certain characters like ., (, ), ?, etc. by prefixing them with a backslash (\).
var str = "Thebestthingsinlifearefree";
var patt = /[0-9A-Za-z !\\#$%&\(\)*+,\-\.\/:;<=>\?#\[\]^_`\{|\}~]/;
var res = !patt.test(str);
console.log(res);
This will print false, as expected.

Related

Return true if two or more repeated chars

The regular expressions I have tried include following:
1> var temp = "(.)\\1{2,}";
2> var temp = "^(?!.*(.)\\1{2,})";
testExp = new RegExp(temp);
The output I get is :
testExp.test("sss is true")
testExp.test("ss is false")
testexp.test("sdsdsd is false") //which should be true.
that is my regular expressions take into account only consecutive repeated characters and not others.
You may add .* before \1 (to match any 0+ chars other than line break chars) and use the following regex:
/(.)(?:.*\1){2,}/
Or, if there can be line breaks in the input string:
/([\s\S])(?:[\s\S]*\1){2,}/
See the regex demo. [\s\S] (or [^] in JS regex) will match any char while . matches any char but a line break char.
Details
(.) - capturing group #1 matching any 1 char
(?:.*\1){2,} - 2 or more consecutive occurrences of:
.* - any 0+ chars other than line break chars
\1 - backreference to Group 1 value (same char as captured in Group 1).
Try somethink like :
var str="sdsdsd";
var hasDuplicates = (/([a-zA-Z]).*?\1/).test(str)
alert("repeating string "+hasDuplicates);
var text = 'abcdeaf';
if (text.match(/(.).*\1/) {} else {}

Merge contiguous "," into a single "," and remove leading and trailing "," in one RegExp

Suppose I have a string
",,,a,,,,,b,,c,,,,d,,,,"
I want to convert this into
"a,b,c,d"
in 1 RegExp operation.
I can do it in 2 RegExp operations like
var str = ",,,a,,,b,,,,c,,,,,,,,d,,,,,,";
str = str.replace(/,+,/g,",").replace(/^,*|,*$/g, '');
is it possible to do this in 1 RegExp operation ?
You could use a regular expression, which are at start or are followed by a comma or at the and and replace it with an empty string.
/^,*|,(?=,|$)/g
1st Alternative ^,*
^ asserts position at start of the string
,* matches the character , literally (case sensitive)
* Quantifier ā€” Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
2nd Alternative ,+(?=,|$)
,+ matches the character , literally (case sensitive)
+ Quantifier ā€” Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
Positive Lookahead (?=,|$)
Assert that the Regex below matches
1st Alternative ,
, matches the character , literally (case sensitive)
2nd Alternative $
$ asserts position at the end of the string
Global pattern flags
g modifier: global. All matches (don't return after first match)
var string = ",,,a,,,,,b,,c,,,,d,,,,";
console.log(string.replace(/^,*|,+(?=,|$)/g, ''));
The approach below returns expected result using two processes. .match() and template literal, which casts the encapsulated javascript expression to string when assigned to a variable.
You can use String.prototype.match() with RegExp /[^,]+/ to negate matching comma character ,, match one or more characters other than ,, including + in RegExp following character class where , is negated to match "abc" as suggested by #4castle; template literal to cast resulting array to string.
var str = ",,,a,,,b,,,,c,,,,,,,,d,,,efg,,,";
str = `${str.match(/[^,]+/g)}`;
console.log(str);

How do I make my limit match greedy?

The following code only matches MN. How do I get it to match KDMN?
var str = ' New York Stock Exchange (NYSE) under the symbol "KDMN."';
var patt = new RegExp("symbol.+([A-Z]{2,5})");
var res = patt.exec(str);
console.log(res[1]);
You may use a lazy +? quantifier:
/symbol.+?([A-Z]{2,5})/
^
See the regex demo. If you keep the greedy .+, it will match as many characters as possible, and will only leave the minimum 2 chars for the next subpattern.
Or, I'd rather make this a bit more verbose:
/symbol\s+"([A-Z]{2,5})/
See another regex demo. The symbol matches a literal string symbol, \s+ will match 1 or more whitespaces, " will match a double quote, and ([A-Z]{2,5}) will capture 2 to 5 uppercase ASCII letters into Group 1.

Regex replace total string

I have and XML file with items that contain this string:
<field name="itemid">xx</field>
Where xx = a number from 50 to 250.
I need to remove the entire string from the whole file.
How would I do this with a Regex replace?
you can use this:
str = str.replace(/<.*>/g,'');
See an example for match here
var str = "<field name='itemid'>xx</field>";
str = str.replace(/<.*>/g, 'replaced');
console.log(str)
Explanation:
< matches the character < literally
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
> matches the character > literally
g modifier: global. All matches (don't return on first match)
If you want to be more restrictive you can do this:
str = str.replace(/<field name\=\"\w*\">\d*<\/field>/g, '');
See an example for match here
var str = '<field name="test">200</field>';
str = str.replace(/<field name\=\"\w*\">\d*<\/field>/g, 'replaced');
console.log(str)
Explanation:
<field name matches the characters
\= matches the character = literally
\" matches the character " literally
\w* match any word character [a-zA-Z0-9_]
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
\" matches the character " literally
> matches the character > literally
\d* match a digit [0-9]
- Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
< matches the character < literally
\/ matches the character / literally
field> matches the characters field> literally (case sensitive)
g modifier: global. All matches (don't return on first match)
When you replace a tag especially XML tag you must be sure that you capture everything from opening to closing tag. In this case RegExp should look back.
var re = /<(\S+)[^>]*>.*<\/\1>/g;
var m ='some text <ab id="aa">aa <p>qq</p> aa</ab>test test <p>paragraph </p>'.replace(re,'');
console.log(m);//some text test test
\1 matches (\S+)
\S+ one or more non-white-space characters

field validation for string along with number in javascript

I have a password field in one form. Now I have to validate in such a way that the field value should be a 7 digits string along with a number. Otherwise it will return false.
Please help me.
Create regex first
Var regex = /\w{7}\d/i;
var yourvalue=$("#passwordid").value;
regex.test(yourvalue){
return true;
}
else{
return false
}
Iā€™m sure there is a better way, but something like:
if ( /.{7}/.test(str) && /\d/.test(str) ) {
//OK
}
In your javascript you can use the RegExp object.
var regEx = new RegExp(pattern, modifiers);
or more simply:
var pattern = /pattern/modifiers;
E.g.
var password = "abcdefg1";
var pattern = /\w{7}\d/i;
var isMatch = pattern.test(password);
Here are some expressions:
[abc] Find any character between the brackets
[^abc] Find any character not between the brackets
[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase z
[A-z] Find any character from uppercase A to lowercase z
[adgk] Find any character in the given set
[^adgk] Find any character outside the given set
(red|blue|green) Find any of the alternatives specified
Metacharacters:
. Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word
\B Find a match not at the beginning/end of a word
\0 Find a NUL character
\n Find a new line character
\f Find a form feed character
\r Find a carriage return character
\t Find a tab character
\v Find a vertical tab character
\xxx Find the character specified by an octal number xxx
\xdd Find the character specified by a hexadecimal number dd
\uxxxx Find the Unicode character specified by a hexadecimal number xxxx
Quantifiers
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y n's
n{X,} Matches any string that contains a sequence of at least X n's
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
?=n Matches any string that is followed by a specific string n
?!n

Categories

Resources