正则表达式并忽略空格 [英] Regex and ignore whitespace
问题描述
我有以下正则表达式,用于在文件字符串搜索中匹配各种信用卡号.但是,如果要匹配的模式前后有空格,则匹配将失败.
I have the following regex that I am using to match on various credit card numbers within a string search of files. However, if there is a space before or after the pattern to match, then the match will fail.
$CC_Regex = "^(\d{4}-){3}\d{4}$|^(\d{4} ){3}\d{4}$|^\d{16}$"
例如,它会匹配前三名,但不会匹配后三名.
For example, it will match the top three, but will not match the bottom three.
1111-2323-2312-3434
1234343425262837
1111 2323 2312 3434
1111-2323-2312-3434
1234343425262837
1111 2323 2312 3434
在后三个中,第一个末尾有一个空格,第二个前面有一个空格,第三个前后有一个空格.
Out of the bottom three, the first one has a space at the end of it, the second one has a space before it, and the third one has a space before and after it.
预先感谢您的帮助.
推荐答案
扩充正则表达式以处理前端和末尾的空格很容易:
It would be easy enough to augment the regex to handle whitespace at the front and end:
^\s*(?:(\d{4}-){3}\d{4}|(\d{4} ){3}\d{4}|\d{16})\s*$
但取字符串似乎更谨慎,删除除数字以外的所有内容,然后检查它是否为 16 位数字:
but it seems more prudent to take the string, remove everything except digits, and then check if it's a 16-digit number:
$result = $subject -creplace '[^0-9]+', ''
$found = $result -cmatch '^[0-9]{16}$'
毕竟,谁知道人们可能对格式有什么想法 - 组之间的几个空格,空格和破折号的混合等等...
After all, who knows what ideas people might have for formatting - several spaces between groups, mixes of spaces and dashes etc...
这篇关于正则表达式并忽略空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!