简体   繁体   中英

Powershell regex matching various Serial numbers

I am trying to create regex that will match serial number for various devices. the match is a mix of letters and numbers at least 6 characters long. I am terrible with regex, all I have been able to get to work is $Serial -match '\d\D' but this does not verify the length. I have tried '\d{0-6}\D{0-6}' but it does not get a match. Could anyone provide an appropriate regex for serial numbers. These are from different device types and all have a slightly different format. Here is list of examples:

1VWPGF1
22P342Y4
2M251434B9
2TK95004x4
5CG934322D
8CG4322TVF
BRJ9323XR5
CND8432NVJ
MXL64322Q4
MXL64324MV
PF1CZ0EF
USE147SX0Y
USH7432L1W

You may use the following:

$Serial -match '[A-Z0-9]{6,}'

[] denotes a character class. Inside you have a range of characters A through Z and 0 through 9 . {6,} matches 6 or more times the current match (0-9 or AZ). Normally AZ is case sensitive in regex, but the -match operator is not. If you want uppercase matches only, I recommend changing to -cmatch , the case-sensitive variant.

If you're not worried about case-sensitivity or underscores, here's an even shorter version

$serial -match '[\w]{6,}'

It's not suitable if you might have underscores in the strings that you need to exclude.

Also, I recommend sites like https://regex101.com/ for testing your regexes. You can see the results real-time, and there are helpful syntax guides on the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM