S
S
ScarletFlash2018-09-03 15:36:26
JavaScript
ScarletFlash, 2018-09-03 15:36:26

How to combine regular expressions?

Hello.
The task is as follows: in the input field we enter either an IP or a URL. They need to be validated, for which I decided to use regular expressions, putting them in a separate file, so that it would be more convenient to manage them.
The file is now written as follows:

const urlPattern = '^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$';
const ipPattern =
    '^(1?\d{1,2}|2[0-4]\d|25[0-5])\.' +
    '(1?\d{1,2}|2[0-4]\d|25[0-5])\.' +
    '(1?\d{1,2}|2[0-4]\d|25[0-5])\.' +
    '(1?\d{1,2}|2[0-4]\d|25[0-5])\/?(\b|\/32)$';

export const urlPatternExp: RegExp = new RegExp(urlPattern);
export const ipPatternExp: RegExp = new RegExp (ipPattern);
export const ipOrUrlPatternExp: RegExp = new RegExp (`(${urlPattern})|(${ipPattern})`, 'g');

( ipPattern is written in such a way that the linter does not swear at the length of the line.)
The idea is to form sets of patterns, assemble them into regular expressions in various configurations, and use them throughout the application.
On regEx101 (in JS mode), there are 2 complete matches. You can try it yourself:
(^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$)|(^(1?\d{1,2}|2[0-4]\d|25[0-5])\.(1?\d{1,2}|2[0-4]\d|25[0-5])\.(1?\d{1,2}|2[0-4]\d|25[0-5])\.(1?\d{1,2}|2[0-4]\d|25[0-5])\/?(\b|\/32)$)
  • name.com
  • 192.168.1.1

The application uses Angular. In reactive forms, validation is written like this:
url: [
            '',
            [ Validators.required, Validators.pattern(ipOrUrlPatternExp) ]
      ],

When manually testing the form in the application, name.com passes validation, and 192.168.1.1 gives an error.
I would be eternally grateful if you tell me why.
UPD.: Solution in the comment to the question.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
PloAl, 2018-09-03
@PloAl

Perhaps the operator or || written incorrectly.

export const ipOrUrlPatternExp: RegExp = new RegExp (`(${urlPattern})|(${ipPattern})`, 'g');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question