Regex select hostname only

Viewed 184

How to adjust the regex below to ignore network address and comments with # and just match hostname?

regex:

^((?!\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b).)*$

string:

localhost,127.0.0.1
8.8.8.8;web
web2 # Comments
192.168.0.1,fw

output:

enter image description here

desired output:

  • localhost
  • web
  • web2
  • fw
1 Answers

You may use

#.*|([\d_]*[A-Za-z]\w*)

See the regex demo.

Only keep Group 2 matches, the rest can be dropped. If you use re.findall, it will fetch empty items where #.* matched, so you may simply remove all empty matches upon re.findall call.

Details:

  • #.* - # and the rest of the line
  • | - or
  • ([\d_]*[A-Za-z]\w*) - Capturing group 1:
    • [\d_]* - zero or more digits or underscores
    • [A-Za-z] - an ASCII letter
    • \w* - zero or more word chars (any letters, digits, underscores)

See Python demo:

import re
text = '''localhost,127.0.0.1
8.8.8.8;web
web2 # Comments
192.168.0.1,fw''' 
print ([x for x in re.findall(r'#.*|([\d_]*[A-Za-z]\w*)', text) if x])
# => ['localhost', 'web', 'web2', 'fw']
Related