正则表达式并忽略空格
我有以下正则表达式,用于在文件字符串搜索中匹配各种信用卡号。但是,如果要匹配的模式之前或之后有空格,则匹配将失败。
$CC_Regex = "^(\d{4}-){3}\d{4}$|^(\d{4} ){3}\d{4}$|^\d{16}$"
例如,它将匹配前三名,但不会匹配后三名。
1111-2323-2312-3434
1234343425262837
1111 2323 2312 3434
1111-2323-2312-3434
1234343425262837
1111 2323 2312 3434
在下面的三个中,第一个的末尾有一个空格,第二个的前面有一个空格,第三个的前后都有一个空格。
预先感谢您的帮助。
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.
Thanks in advance for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
增强正则表达式来处理前端和末尾的空格是很容易的:
但更谨慎的做法是获取字符串,删除除数字之外的所有内容,然后检查它是否是 16 位数字:
毕竟,谁知道是什么人们可能对格式有一些想法 - 组之间有几个空格,空格和破折号的混合等等......
It would be easy enough to augment the regex to handle whitespace at the front and end:
but it seems more prudent to take the string, remove everything except digits, and then check if it's a 16-digit number:
After all, who knows what ideas people might have for formatting - several spaces between groups, mixes of spaces and dashes etc...
我不知道如何在 PowerShell 中具体执行此操作,但使用某种 Replace() 函数来删除空格(或 PowerShell 中的等效函数)会容易得多。
编辑:实际上,首先删除所有内容会更有意义。您可以使用 RegEx 轻松做到这一点:
I don't know how specifically to do this in PowerShell, but it'd be a lot easier to use some sort of replace() function to get rid of the spaces (or the equivalent in PowerShell).
EDIT: Actually, it'd make more sense to remove everything that's not a digit first. You could do that with RegEx easily:
即使存在前导或尾随空白字符(
\s
表示任何空白字符),也会使其匹配。will make it match even if leading or trailing whitepsace is present (
\s
means any whitespace character).这个
^(?\s{0,}\d{4}-{0,}\s{0,}\d{4}-{0,}\s{0, }\d{4}-{0,}\s{0,}\d{4}).*?
How about this
^(?<myregex>\s{0,}\d{4}-{0,}\s{0,}\d{4}-{0,}\s{0,}\d{4}-{0,}\s{0,}\d{4}).*?