简体   繁体   中英

Javascript regex to compare two strings

I want to compare two string using regex in javascript.

Following is the requiremet -

String1 = 'xyz.east.abc.com'

String2 = 'xyz.*.abc.com'

String3 = 'pqr.west.efg.com'

String4 = 'pqr.*.efg.com'

I want a regular expression by using which I should be able to compare above strings and the output should be String1 & String2 are same and String3 & String4 are same.

I have tried using different combination but I was not able to figure out the correct regex to perform the task.

You may implement a tiny function that would do that for you:

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\+\?\.\\\^\$\|]/g, "\\$&");
}

function fuzzyComparison(str, mask) {
    var regex = '^' + escapeRegExp(mask).replace(/\*/, '.*') + '$';
    var r = new RegExp(regex);

    return r.test(str);
}

So what you do here is escape all regex meta characters but * , which you in turn replace with .* which means "any number of any characters".

Then you test the created regular expression against the string you're comparing to.

This solution is better (for the task as you explained it) than using regex literals since you don't need to hardcode all the target regexes and can do that in run time.

JSFiddle: http://jsfiddle.net/60b78b8o/

^xyz\.[^.]*\.abc\.com$

You can use this for string 1 and string 2 .Change abc to efg to match string 3 and string 4 .See demo.

https://regex101.com/r/tJ2mW5/19

You could use /xyz.[az]*.abc.com/ to match any string which start xyz., then has a combination of az charectors, then ends .abc.com

var x = /xyz.[a-z]*.abc.com/.test("xyz.etetjh.abc.com");
//or
var x = /xyz.[a-z]*.abc.com/.test("xyz.east.abc.com");

console.log(x); // will output true.

This will only allow az in the variable section, so you'd need to amend that if you want numbers, case sensitive etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM