MAC Address regex validation for comma separated, colon or dash delimited values

问题: I am using the following Regex for validating MAC Addresses: pattern("^([a-fA-f0-9]){12}(,s*([a-fA-f0-9]){12})*$") and it works fine for the following input: 12aeab...

问题:

I am using the following Regex for validating MAC Addresses:

pattern("^([a-fA-f0-9]){12}(,s*([a-fA-f0-9]){12})*$")

and it works fine for the following input:

12aeabc11bba,662baea1abc2

I'd like to improve it to support the following MAC Address styles:

12-ae-ab-c1-1b-ba,66-2b-ae-a1-ab-c2
12ae-abc1-1bba,662b-aea1-abc2
12:ae:ab:c1:1b:ba,66:2b:ae:a1:ab:c2
12ae:abc1:1bba,662b:aea1:abc2
12aeabc11bba,662baea1abc2

It is not required for the Regex to support the following MAC Address styles, however it is OK if the Regex permits these:

12:ae:ab:c1:1b:ba,66-2b-ae-a1-ab-c2
2134:12:12:1234,ae-12-ae-42-62-ae
ae12-bc33-a122,fe12:ae12:ab54
ae12:bc33-a122

I am using Angular5, and this validation is passed to the FormBuilder validation, so I don't think I can put in multiple patterns.

this.requestForm = this.fb.group({
    macAddresses: ['', [Validators.required, Validators.pattern("^([a-fA-f0-9]){12}(,s*([a-fA-f0-9]){12})*$")]]
});

Can anyone help solve the problem?

Whoever answers this question with the cleanest solution will get a bounty award of 100 rep


回答1:

Try this Regex:

^[a-fA-F0-9]{2}(?:[:-]?[a-fA-F0-9]{2}){5}(?:,[a-fA-F0-9]{2}(?:[:-]?[a-fA-F0-9]{2}){5})*$

Click for Demo

Explanation:

  • ^ - asserts the start of the line
  • [a-fA-F0-9]{2} - matches 2 occurrences of either a digit or a letter in the range a-f or A-F
  • (?:[:-]?[a-fA-F0-9]{2}){5} - matches 0 or 1 occurrence of either a : or -. followed by 5 occurrences of either a digit or a letter in the range a-f or A-F
  • (?:,[a-fA-F0-9]{2}(?:[:-]?[a-fA-F0-9]{2}){5})* - Matches a , followed by the MAC address. The * at the end indicates 0+ occurrences of , followed by MAC address.
  • $ - asserts the end of the line.
  • 发表于 2019-02-21 15:26
  • 阅读 ( 258 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除