Search code examples
regexregex-group

regex to get the values based on the dot selection


I have some of the host names as provided below, i am looking to extract only last three names after dot .

linux7.4q22018.am.nomas.net
uskbkriq01v.na-rdc.pro.com
dtc2233.dti.us-cdc.pro.com
atgrk01labt001v.at-cdc.rci.rs.pro.com
atgrk01labt002v.at-cdc.rci.rs.pro.com

My trial:

I am using below rgex which extracts everything what what it gets after hostname conatining the first dot . itself

([?\.].*)

Result

  .4q22018.am.nomas.net
  .na-rdc.pro.com
  .dti.us-cdc.pro.com
  .at-cdc.rci.rs.pro.com
  .at-cdc.rci.rs.pro.com

Expected:

  am.nomas.net
  na-rdc.pro.com
  us-cdc.pro.com
  rci.rs.pro.com
  rci.rs.pro.com

Solution

  • Use:

    [^.]+\.[^.]+\.[^.]+$
    

    Each [^.]+ matches a sequence of non-dot characters. So this matches 3 of them separated by .. And $ makes it match at the end of the string, so it matchest the last 3 groups.