How to check if a string matches the correct regular expression pattern?

I am working on a registration script for my client product sales website.

I am currently working on a credential entry area, and I want to make sure that the reference identifier is in the correct payment method settings.

The link ID will look something like this: XXXXX-XXXXX-XXXXX

I am trying to use this RegEx pattern to match it: /(\w+){5}-(\w+){5}-(\w+){5}/

This matches it perfectly, but also matches XXXXX-XXXXX-XXXXXXXXXX

Or at least he finds a match there. I want it to fit the whole line. I'm not too familiar with RegEx

How can i do this?

+4
source share
9 answers

You need to use start and finish bindings. Alternatively, if you do not need to capture these groups, you can omit the parentheses.

In addition, +{5} means a match more than once exactly 5 times. I believe that you did not want this, so I dropped + .

 /^\w{5}-\w{5}-\w{5}\z/ 

Also, I used \z so that your string does not match "abcde-12345-edcba\n" .

+8
source

Use ^ and $ to match the beginning and end of the input line, respectively.

Also note that using + was redundant since (\w+){5} means "a word character at least once, five times," which means that it can match at least five times. You probably meant (\w){5} (or just \w{5} if you don't need a backlink, I will assume in my example that you are doing this).

 /^(\w){5}-(\w){5}-(\w){5}$/ 
+9
source

put the regex between ^ and $ to match the whole string and check if it matches anything

Example:

 /^(\w+){5}-(\w+){5}-(\w+){5}$/ 
+2
source

Try

 /^([\w]{5,5})-([\w]{5,5})-([\w]{5,5})$/i 

There are several online regexp testers that I work with this one before I code.

+1
source

Use ^ and $ to indicate the beginning and end of a regular expression string:

 /^\w{5}-\w{5}-\w{5}$/ 

http://www.regular-expressions.info/anchors.html

0
source

Include it in "^" and "$", thus:

 /^(\w+){5}-(\w+){5}-(\w+){5}$/ 
0
source

/^(\w){5}-(\w){5}-(\w){5}$/
You need to explicitly say that you want the template to start at the beginning of the line and end when it ends.
You can improve it: /^((\w){5}-){2}(\w){5}$/ ; that way, you can easily change the number of items your serial number can have.

0
source

You need ^ combine the beginning of the line and $ so that it matches the end:

 /^\w{5}-\w{5}-\w{5}$/ 

Note that (\w+){5} incorrect because it means five repetitions of \w+ , but this, in turn, means "one or more word characters."

0
source

In preg, \ b marks the boundaries of words. So you can try something like

 /\b(\w+){5}-(\w+){5}-(\w+){5}\b/ 
-1
source

Source: https://habr.com/ru/post/1347262/


All Articles