Convert string to RegExp - javascript

How can I check a JavaScript string is in a RegExp format, then convert it to RegExp?
I found a way with RegExp, but the rule is too complex to make it right.
function str2Regex(str){
var rule = /\/(\\[^\x00-\x1f]|\[(\\[^\x00-\x1f]|[^\x00-\x1f\\\/])*\]|[^\x00-\x1f\\\/\[])+\/([gim]*)/;
var match = str.match(rule);
return match ? new RegExp(match[1],match[3]) : str;
}
Now I'm using /\/(.*)\/(?=[igm]*)([igm]*)/ which works.

The simplest way, and probably the most correct, is to use try/catch :
try {
r = new RegExp(str);
} catch(error) {
// no good
}
You get a SyntaxError when the string doesn't match a well formed regular expression.
If you want to test a string whose value is like a compiled regular expression (for example "/\b=\b/g", you can use such a function :
function checkCompiledRegex(str) {
if (str[0]!='/') return false;
var i = str.lastIndexOf('/');
if (i<=0) return false;
try {
new RegExp(str.slice(1, i), str.slice(i+1));
} catch(error) {
return false;
}
return true;
}

Related

Convert Javascript regex to Typescript regex

I have a regex which checks the inputText is in valid url format or not.
And working almost good:
checkUrlFormat() {
const pattern = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
if (pattern.test(this.inputText) || this.inputText == null) {
return false;
}
return true;
}
But i need to make that pattern shorter so I have written a regexp in https://www.debuggex.com/#cheatsheet as
(((http|https)(://))?((www).)?)[a-z0-9]+(.|[a-z0-9])+[a-z0-9]
but it is in javascript format and i could not find how to use that string with the code above. When i directly copy paste it, it is giving syntax error. How can i combine them.
checkUrlFormat() {
const pattern = /^(((http|https)(:\/\/))?((www).)?)[a-z0-9]+(.|[a-z0-9])+[a-z0-9]$/;
if (pattern.test(this.inputText) || this.inputText == null) {
return false;
}
return true;
}

construct string from regular expression and results (inverse for matching)

There is any reliable way to construct string from given regex and "matched" results?
i am looking for something like:
stringConstruct('/My name is (?P<name>.*)/', {name: John});
with result "My name is John". So I need inverse functionality to regexp match.
Answer in any nonexotic language is suitable.
The short answer is "No" - that is not what regex is for.
but, you could do something like:
function stringConstruct($stringTemplate, $regex, $input){
if(preg_match($regex, $input)){
return str_replace($regex, $input, $stringTemplate);
} else {
return false;
}
}
But, you would have to use it like this, instead:
echo stringConstruct('My name is /(?P<name>.*)/', '/(?P<name>.*)/', "John");
You can write your own function. I did it once in Java, here's an example. sb is a string to be worked on. replaceMap is a (regexp, replaceStr) map:
public static boolean replaceAll(StringBuffer sb, Map<String,String> replaceMap)
{
boolean altered = false;
Iterator<String> it = replaceMap.keySet().iterator();
while (it.hasNext())
{
String toReplace = it.next();
Matcher mat = Pattern.compile(toReplace).matcher(sb);
while (mat.find())
{
if (!altered)
{
altered = true;
}
String str = (String) replaceMap.get(toReplace);
sb.replace(mat.start(), mat.end(), str);
mat.region(mat.start() + str.length(), sb.length());
}
}
return altered;
}

global replace doesn't work , but simple replace works fine

i have a simple smily parser code :
for (var key in smiles) {
text = text.replace(key , smiles[key]);
}
return text;
so the problem is , this will only replace the first one so i've switched to global replace
for (var key in smiles) {
var r = '/'+key+'/g';
console.log(r);
text = text.replace(r , smiles[key]);
}
in console i have :
/:)/g
/;)/g
/:(/g
which seems to be ok , but it wont replace any of these codes :) ;) :(
whats wrong ?
A regular expression literal (/foo/g) is not the same as a string that looks like a regular expression literal ("/foo/g").
You can create regular expressions dynamically using the RegExp constructor:
var r = new RegExp(key, 'g');
And that’s the point at which you’ll get parenthesis-related errors. You can escape your values to put in a regular expression – put together in the nicest way, it might look something like this:
function escapeRegex(text) {
return text.replace(/[[{}()*+?.\\^$|]/g, "\\$&");
}
function replaceAll(str, map) {
var re = new RegExp(Object.keys(map).map(escapeRegex).join("|"), "g");
return str.replace(re, function(m) {
return map[m];
});
}
Just keep looping through the text and replacing the smiley until there are no more occurrences:-
for (var key in smiles) {
while (text.indexOf(key) > -1) {
text = text.replace(key, smiles[key]);
}
}
return text;

Regex Javascript in order to know if a pattern is containing in a String

I have a JavaScript String, for example :
var test1 = "aaaaaa#bbbbb.temp" ; // Function must return true in this case
var test2 = "ccccc#ddddd.fr " ; // Function must return false in this case
I would like to build a function which return true if the String contains # character, following by any character "bbbbbb" following by ".temp" extension.
How can I do this ?
You can use regex#test
var found = /#.*?\.temp\b/.test(str);
If you want to make it # character, following by "bbbbbb" following by ".temp" extension then use:
var found = /#bbbbbb\.temp\b/.test(str);
Regular expression solution:
function validate(argument) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if((argument.lastIndexOf('.temp', argument.length-5)>=argument.length-5) && re.test(argument)) {
return true;
} else {
return false;
}
}
JsFiddle test: http://jsfiddle.net/2EXxx/

Using JavaScript RegExp to valid email. Regex special characters not working

I've got this JavaScript function:
function emailaddresscheck() {
var emailregex = new RegExp("[A-Z0-9._%+-]+#[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)");
var emailstring = $("#email-address").val();
if (emailregex.test(emailstring)) {
$("#email-address-check").fadeIn(100);
return true;
}
else if ($("#email-address").val().length <= 5) {
$("#email-address-check").fadeOut(100);
return false;
}
}
The if condition is firing if I have a simple string in the RegExp constructor but this more complex regex isn't working.
Where am I going wrong?
UPDATE:
This is the finished working code:
function emailaddresscheck() {
var emailregexp = new RegExp("^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\\.(?:[A-Za-z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$");
var emailstring = $("#email-address").val();
if (emailregexp.test(emailstring) === true) {
$("#email-address-check").fadeIn(100);
return true;
}
else if (emailregexp.test(emailstring) === false) {
$("#email-address-check").fadeOut(100);
return false;
}
}
When you create a regex with the RegExp constructor you need to double escape special characters since they are inside a string.
new RegExp("[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)");
-^-
Or just use a literal regex:
/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)/

Categories