6

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.

2
  • RegExp Commented Mar 24, 2015 at 10:44
  • Is the asterisk (*) symbol here a character or a wildcare? Commented Mar 24, 2015 at 10:52

3 Answers 3

5

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks zerkms. This is the exact solution I was looking for & Thanks for explaining the logic also.
2
^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

Comments

1

You could use /xyz.[a-z]*.abc.com/ to match any string which start xyz., then has a combination of a-z 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 a-z in the variable section, so you'd need to amend that if you want numbers, case sensitive etc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.