Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I have regex to match exact multiple domains without anything in front or end?

I'd like to whitelist domains and I have this list as

(domain1.com|domain2.com)

However, it will still match to

ci.domain1.com

https://regex101.com/r/A2IOJE/1/

I'm writing the code in node.js

Here's the code

new RegExp('(domain1.com|domain2.com)', 'igm').test('ci.domain1.com');
like image 645
toy Avatar asked Oct 15 '25 14:10

toy


2 Answers

You just need to add ^ (start of string) & $ (end of string):

/^(domain1.com|domain2.com)$/

console.log(
new RegExp('^(domain1.com|domain2.com)$', 'igm').test('ci.domain1.com'),
new RegExp('^(domain1.com|domain2.com)$', 'igm').test('domain1.com'),
new RegExp('^(domain1.com|domain2.com)$', 'igm').test('domain2.com')
)
like image 62
cn007b Avatar answered Oct 18 '25 07:10

cn007b


With anchors and optional www matching at the start you can use this regex:

/^(?:www\.)?(?:domain1|domain2)\.com$/i

Also dot before com needs to be escaped to avoid matching any character.

RegEx Demo

RegEx Breakup:

  • ^: Start
  • (?:www\.)?: Match optional www at the start of domains
  • (?:domain1|domain2): Match domain1 or domain2
  • \.com: Match literal text .com
  • $: End
like image 41
anubhava Avatar answered Oct 18 '25 08:10

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!