tags:

views:

71

answers:

3

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

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

Thanks

+5  A: 
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.

Tim Pietzcker
Sorry, I misread the question at first. Have edited my answer...
Tim Pietzcker
A: 
result = subject.gsub(/^[^a-zA-Z]+/, '').gsub(/[^a-zA-Z]+$/, '')
ChaosR
Hey, I edited, it works now!
ChaosR
It will still fail if the string contains newlines (or non-ASCII letters).
Tim Pietzcker
I suppose it would, yours is better, hehe.
ChaosR
+1  A: 

In ruby 1.9.1 :

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

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

steenslag