[Ruby] I want to extract between the character strings with a regular expression

less than 1 minute read

I took some time to extract the space between the strings, so take a note.

Background

The front and back of the character string are fixed, and the characters between

Example:
I want to extract the service name part from the file name or constant that concatenates the following

COMPANY_SERVICE_OPTION
*The naming convention is Service Company_Service Name_OPTION

pattern 1

Reference here


"COMPANY_SERVICE_OPTION".slice(/COMPANY_(.+)_OPTION/)
puts $+

SERVICE

”$+” is a built-in variable of Ruby, and there are various other patterns [https://techracho.bpsinc.jp/hachi8833/2017_01_31/33351). However, since it was found that there was a description of deprecation, the following pattern 2 was used.

pattern 2

Reference this gsub description


puts "COMPANY_SERVICE_OPTION".gsub(/COMPANY_(.+)_OPTION/,'\+')

SERVICE

Pattern 3 (Additional)

How to comment from scivola


"COMPANY_SERVICE_OPTION".match(/COMPANY_(.+?)_OPTION/)[1]

SERVICE

that’s all. If you like us, follow us on Qiita or Twitter, we’ll be excited! If you have other options, please feel free to comment. Thanking you in advance~

Reference

I want to extract the character string between regular expressions Try to write special variables of [Ruby] Kernel without $ sign as much as possible String-Ruby Reference Manual