regex - Powershell Regex 验证计算机名称
问题描述
我喜欢这个网站,人们非常乐于助人......
这是一个更具体的问题,但参考(https://stackoverflow.com/questions/62580859/using-regex-for-complicated-naming-convention)
@Witker和@AdminofThings都为我正在开发的计算机名称验证检查器解决了一个大问题。谢谢你俩!.
我之前给出的例子是我可以用来构建的东西。但是我有一个小问题,我无法用正则表达式的一部分来匹配特殊标识符。让我解释:
我需要一个可以解析这些数字集的正则表达式(磅符号就是任何数字):
1######
2######
3######
4######
37#####
47#####
为了更好地理解,我需要查看任何一组 6 个数字的前两位数字,看看它们是否符合其中一个标准。以下是一些匹配示例:
234556 <-- single match [2]
012345 <-- no match [0]
346980 <-- single match [3]
379456 <-- double match [37]
435794 <-- single match [4]
471234 <-- double match [47]
171234 <-- single match [1] not double match [17]
我看到的问题是,当 1 后跟 7 时,它的匹配为两位数;但我需要它来看到它 1 是一个单一的标识符。
如果我使用不同的正则表达式,当我需要将 37 匹配为双 37 时,我会看到 37 是单匹配。
我希望我可以在一个正则表达式中完成所有这些操作,而无需执行 if else 语句。我尝试过的正则表达式是:
(?<identifier>[1234](7)?)
(?<identifier>[1234]([34]7)?)
(?<identifier>[1234]([34|47])
(?<identifier>[1234]\d{1}|[37|47]\d{2})
(?<identifier>[1234]|37|47)
(?<identifier>1|2|3|4|37|47)
请帮助...再次。;)
解决方案
如果我正确理解您的要求,您可以使用以下模式:
\b(?=.{6}\b)(?<identifier>37|47|[1234])\d+
演示。
分解:
\b # Word boundary assertion.
(?=.{6}\b) # A Lookahead to make sure the number is exactly 6 digits.
(?<identifier> # Start of the 'identifier' capturing group.
37|47 # Search for '37' or '47' first.
|[1234] # If not found, search for any digit in this character class.
) # End of the capturing group
\d+ # Match any number of digits (max. 6 in total because of the Lookahead).
如果您只关心标识符并且不想在匹配中包含剩余的数字(但仍想确保它们在那里),您可以将上面的模式更改为:
\b(?=\d{6}\b)(?<identifier>37|47|[1234])
演示。
..或者在没有捕获组的情况下使其更简单:
\b(?=\d{6}\b)(?:37|47|[1234])
推荐阅读
- c - 使用常量内存/不使用数组计算方差
- vba - 仅在有约会时发送电子邮件 (Outlook)
- memory-leaks - curl_open 内存泄漏
- android - FirestoreRecyclerAdapter 中的 onBindViewHolder 没有被调用?
- python - Tensorflow 2.2.0 :- 警告:tensorflow:在最小化损失时,变量不存在梯度
- javascript - Javascript 函数的字符限制不会更新 HTML
- c# - 如何在asp.net,c#中获取客户端设备信息
- c# - Oxyplot Plotmodel High AxisTickLabel 对于多个 Y 轴不完全可读
- python - Google Cloud Speech-To-Text API 响应不返回字词
- php - 无法上传原始 CSV 文件但是