Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Powershell or Regex?

Posted on 2013-05-28
2
Medium Priority
?
407 Views
Last Modified: 2013-05-28
Hi people -

Just curious -
look at the following expression in powershell.  Why does this return true?  I believe the limit here is 3, NO?

"8888888888888888888" -match "[0-9]{0,3}"
0
Comment
Question by:enjama
2 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 2000 total points
ID: 39201216
Because the pattern can locate between 0 and 3 digits. You haven't bounded the pattern, so any sequence of 3 digits within the string will match. In this case, it will be the first three digits.

If you want to make certain the target string is *exactly* 3 digits, then add anchors, specifically the "start of string" and "end of string" anchors, to your pattern.

e.g.

"8888888888888888888" -match "^[0-9]{0,3}$"

Open in new window


More information:  http://www.regular-expressions.info/anchors.html
0
 

Author Closing Comment

by:enjama
ID: 39201690
As a result of this comment, my regex went from

"888-367-1240" -match "[0-9]{3,3}-[0-9]{3}-[0-9]{4}"

to

"888-367-1240" -match "^[0-9]{3,3}-[0-9]{3}-[0-9]{4}$"

and it now works properly.  Thank you!
0

Featured Post

Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windows 10 came with  a lot of built in applications, Some organisations leave them there, some will control them using GPO's. This Article is useful for those who do not want to have any applications in their image (example:me).
Measuring Server's processing rate with a simple powershell command. The differences in processing rate also was recorded in different use-cases, when a server in free and busy states.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Screencast - Getting to Know the Pipeline

916 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question