Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove leading and trailing non-alphabetic characters in ruby

Tags:

regex

ruby

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

for eg. ":----- pt-br:-" , i want "pt-br"

Thanks

like image 926
anusuya Avatar asked Dec 29 '22 12:12

anusuya


1 Answers

result = subject.gsub(/\A[\d_\W]+|[\d_\W]+\Z/, '')

will remove non-letters from the start and end of the string.

\A and \Z anchor the regex at the start/end of the string (^/$ would also match after/before a newline which is probably not what you want - but that might not matter in this case);

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

| is the alternation operator.

like image 71
Tim Pietzcker Avatar answered Apr 13 '23 00:04

Tim Pietzcker