Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to Match String Exactly?

Tags:

I'll preface this question by mentioning that while I'm far from a regular expressions guru, they are not completely foreign to me. Building a regular expression to search for a pattern inside a particular string generally isn't a problem for me, but I have a (maybe?) unique situation.

I have a set of values, say:

028938
DEF567987
390987.456
GHI345928.039

I want to match a certain set of strings, such as:

  • Strings composed of exactly 6 digits
  • Strings composed of exactly 6 digits, a decimal, followed by exactly 3 more digits

In the above examples, the first and third values should be matched.

I'm using the regular expressions:

[0-9]{6} [0-9]{6}.[0-9]{3} 

Unfortunately, since all the above examples contain the specified pattern, all values are matched. This is not my intention.

So my question, in a nutshell, is how to write a regular expression that matches a string exactly and completely, with no additional characters to the right or left of the matched pattern? Is there a term for this type of matching? (Google was no help.) TIA

like image 873
Craig Otis Avatar asked Aug 13 '10 17:08

Craig Otis


People also ask

How do you match exact strings?

We can match an exact string with JavaScript by using the JavaScript string's match method with a regex pattern that has the delimiters for the start and end of the string with the exact word in between those.

How do I match an entire string in regex?

Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.

How do I match a specific character in regex?

Match any specific character in a setUse square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.


1 Answers

use ^ and $ to match the start and end of your string

^[0-9]{6}$ ^[0-9]{6}\.[0-9]{3}$ 

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

Also, as noted by Mikael Svenson, you can use the word boundary \b if you are searching for this pattern in a larger chunk of text.

Reference: http://www.regular-expressions.info/wordboundaries.html

You could also write both those regexes in one shot

^\d{6}(\.\d{3})?$ 
like image 200
CaffGeek Avatar answered Sep 19 '22 14:09

CaffGeek