Ruby look behind regex error: invalid pattern in look-behind

Viewed 276

The challenge calls to capture all characters including the second "."

EG in string: FILE_NAME.EXTENSION.OTHEREXTENSIONadasd^^assdassds34

captured characters should be ".OTHEREXTENSIONadasd^^assdassds34"

Therefore I should end up with: "FILE_NAME.EXTENSION"

The regex I have tried either captures all characters after the first "." or throws up error: invalid pattern in look-behind

First example which brings up error:

string = "FILE_NAME.EXTENSION.OTHEREXTENSIONadasd^^assdassds34"

string.gsub(/(?<=[.]\S+)[.]\S+/, '')

Second example which incorrectly captures '.EXTENSION.OTHEREXTENSIONadasd^^assdassds34':

string = "FILE_NAME.EXTENSION.OTHEREXTENSIONadasd^^assdassds34"

string.gsub(/(?<=[.])\S*?[.]\S*/, '')
1 Answers

You may use

s = s.gsub(/\A([^.]*\.[^.]*)\..*/, '\1')

See the regex demo and the regex graph:

enter image description here

Details

  • \A - start of a string
  • ([^.]*\.[^.]*) - Group 1: 0+ non-dots, a dot and 0+ non-dots
  • \. - a dot
  • .* - any 0 or more chars other than line break chars.
Related