Regular Expression for validating DNS label ( host name)

后端 未结 6 1313
长发绾君心
长发绾君心 2020-12-03 21:11

I would like to validate a hostname using only regualr expression.

Host Names (or \'labels\' in DNS jargon) were traditionally defined by RFC 952 and RFC 1123 and m

6条回答
  •  感动是毒
    2020-12-03 21:34

    A revised regex based on comments here and my own reading of RFCs 1035 & 1123:

    Ruby: \A(?!-)[a-zA-Z0-9-]{1,63}(? (tests below)

    Python: ^(?!-)[a-zA-Z0-9-]{1,63}(? (not tested by me)

    Javascript: pattern = /^(?!-)[a-zA-Z0-9-]{1,63}$/g; (based on Tom Lime's answer, not tested by me)

    Tests:

    tests = [
      ['01010', true],
      ['abc', true],
      ['A0c', true],
      ['A0c-', false],
      ['-A0c', false],
      ['A-0c', true],
      ['o123456701234567012345670123456701234567012345670123456701234567', false],
      ['o12345670123456701234567012345670123456701234567012345670123456', true],
      ['', false],
      ['a', true],
      ['0--0', true],
      ["A0c\nA0c", false]
    ]
    
    regex = /\A(?!-)[a-zA-Z0-9-]{1,63}(?

    Notes:

    1. Thanks to Mark Byers for the original code fragment
    2. solidsnack points out that RFC 1123 allows all-numeric labels (https://tools.ietf.org/html/rfc1123#page-13)
    3. RFC 1035 does not allow zero-length labels (https://tools.ietf.org/html/rfc1035):
    4. I've added a test specifically for Ruby that ensures a new line is not embedded in the label. This is thanks to notes by ssorallen.
    5. This code is available here: https://github.com/Xenapto/domain-label-validation - I'm happy to accept pull requests if you want to update it.

提交回复
热议问题