rubyregexrubular

Select a string in regex with ruby


I have to clean a string passed in parameter, and remove all lowercase letters, and all special character except :

so i have this string passed in parameter:

aA azee + B => C=

and i need to clean this string to have this result:

A + B => C

I do

string.gsub(/[^[:upper:][+|^ ]]/, "")

output: "A + B C"

I don't know how to select the => (and for <=>) string's with regex in ruby)

I know that if i add string.gsub(/[^[:upper:][+|^ =>]]/, "") into my regex, the last = in my string passed in parameter will be selected too


Solution

  • You can try an alternative approach: matching everything you want to keep then joining the result.

    You can use this regex to match everything you want to keep:

    [A-Z\d+| ^]|<?=>
    

    As you can see this is just a using | and [] to create a list of strings that you want to keep: uppercase, numbers, +, |, space, ^, => and <=>.

    Example:

    "aA azee + B => C=".scan(/[A-Z\d+| ^]|<?=>/).join()
    

    Output:

    "A  + B => C"
    

    Note that there are 2 consecutive spaces between "A" and "+". If you don't want that you can call String#squeeze.