Regular expression for exact string matching

I want to match two passwords with a regex. For example, I have two inputs "123456" and "1234567", then the result should not match (false). And when I entered "123456" and "123456", then the result should match (true).

I could not make an expression. How should I do it?

+103
regex
Apr 22 '11 at 6:24
source share
5 answers

if you have an input password in a variable and you want to exactly match 123456, then anchors will help you:

/^123456$/ 

in perl, the password matching test will look like

 print "MATCH_OK" if ($input_pass=~/^123456$/); 

EDIT:

bart kiers is right, why don’t you use strcmp () for this? each language has it in its own way.

as a second thought, you may need a more secure authentication mechanism :)

+133
Apr 22 '11 at 6:29
source share

In the answer, malfaux '^' and '$' are used to determine the beginning and end of the text.
They are commonly used to determine the beginning and end of a line.
However, in this case this may be correct.
But if you want to combine the exact word, the more elegant way is to use '\ b' . In this case, the following pattern will match the exact phrase '123456'.

/ \ b123456 \ b /

+108
Oct 25
source share
 (?<![\w\d])abc(?![\w\d]) 

this ensures that your match is not preceded by any character, number or underscore, and does not immediately follow the character or number or underscore

therefore it will match "abc" in "abc", "abc.", "abc", but not "4abc" nor "abcde"

+25
Apr 16 '14 at 19:01
source share

A more direct way is to verify equality

 if string1 == string2 puts "match" else puts "not match" end 

however, if you really want to stick with regex,

 string1 =~ /^123456$/ 
+6
Apr 22 2018-11-11T00:
source share

You can also try adding space at the beginning and end of the keyword: /\s+123456\s+/i .

+2
Nov 07 2018-11-11T00:
source share



All Articles