Chirayu
Chirayu

Reputation: 4891

Regular expression for exact match of a string

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

I couldn't make the expression. How do I do it?

Upvotes: 256

Views: 1118222

Answers (6)

xerxes
xerxes

Reputation: 9

If you are working in Python, re has a re.fullmatch method, bit easier then modifying the string

Upvotes: 0

Aedna
Aedna

Reputation: 789

(?<![\w\d])abc(?![\w\d])

this makes sure that your match is not preceded by some character, number, or underscore and is not followed immediately by character or number, or underscore

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

Upvotes: 57

prageeth
prageeth

Reputation: 7395

In malfaux's answer '^' and '$' has been used to detect the beginning and the end of the text.
These are usually used to detect the beginning and the end of a line.
However this may be the correct way in this case.
But if you wish to match an exact word the more elegant way is to use '\b'. In this case following pattern will match the exact phrase'123456'.

/\b123456\b/

Upvotes: 210

Bhushan Lodha
Bhushan Lodha

Reputation: 6862

You may also try appending a space at the start and end of keyword: /\s+123456\s+/i.

Upvotes: 4

user237419
user237419

Reputation: 9064

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

/^123456$/

in perl the test for matching the password would be something like

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

EDIT:

bart kiers is right tho, why don't you use a strcmp() for this? every language has it in its own way

as a second thought, you may want to consider a safer authentication mechanism :)

Upvotes: 278

kurumi
kurumi

Reputation: 25599

A more straight forward way is to check for equality

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

however, if you really want to stick to regular expression,

string1 =~ /^123456$/

Upvotes: 5

Related Questions