How to remove leading and trailing non-alphabetic characters in a ruby

I want to remove any leading and trailing non-alphabetic character in my line.

eg. ":----- pt-br:-" , I want "pt-br"

thanks

+4
source share
3 answers
 result = subject.gsub(/\A[\d_\W]+|[\d_\W]+\Z/, '') 

will remove non-letters from the beginning and end of the line.

\A and \Z bind the regular expression at the beginning / end of the line ( ^ / $ will also match after / before the new line, which is probably not what you want - but it may not matter in this case);

[\d_\W]+ matches one or more digits, an underscore, or anything else that is not an alphanumeric character, leaving only letters.

| is an interleave operator.

+9
source

In ruby ​​1.9.1:

 ":----- pt-br:-".partition( /[a-zA-Z](...)[a-zA-Z]/ )[1] 
Section

searches for a pattern in a string and returns the part before it, the match, and the part after it.

+1
source
 result = subject.gsub(/^[^a-zA-Z]+/, '').gsub(/[^a-zA-Z]+$/, '') 
0
source

Source: https://habr.com/ru/post/1314174/


All Articles