Вопрос

Я в настоящее время делаю группу обработки на строке, используя регулярные выражения с gsub(), но я довольно сильно церую себя, что начинает становиться грязным.Можете ли вы помочь мне построить одно Regex для следующего:

string.gsub(/\.com/,'').gsub(/\./,'').gsub(/&/,'and').gsub(' ','-').gsub("'",'').gsub(",",'').gsub(":",'').gsub("#39;",'').gsub("*",'').gsub("amp;",'')
.

в основном вышеупомянутое, удаляет следующее:

    .
  • .com
  • .
  • ,
  • :
  • *
  • коммутаторы '&' for 'и'
  • коммутаторы '' for '-'
  • переключатели "для '' '

    Есть ли более простым способом сделать это?

Это было полезно?

Решение

You can combine the ones that remove characters:

string.gsub(/\.com|[.,:*]/,'')

The pipe | means "or". The right side of the or is a character class; it means "one of these characters".

Другие советы

A translation table is more scalable as you add more options:

translations = Hash.new
translations['.com'] = ''
translations['&'] = 'and'
...

translations.each{ |from, to| string.gsub from, to }

Building on Tim's answer:

You can pass a block to String.gsub, so you could combine them all, if you wanted:

string.gsub(/\.com|[.,:*& ']/) do |sub|
    case(sub)
    when '&'
        'and'
    when ' '
        '-'
    else
        ''
    end
end

Or, building off echoback's answer, you could use a translation hash in the block (you may need to call translations.default = '' to get this working):

string.gsub(/\.com|[.,:*& ']/) {|sub| translations[sub]}

The biggest perk of using a block is only having one call to gsub (not the fastest function ever).

Hope this helps!

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top