Home>
Thing I want to do

I want to allow only half-width spaces, half-width alphanumeric characters, and underscores in () of the character string.

①
"My name is Hogehoge (a_bcd) Fugafuga"


When unnecessary character strings are removed

②
"My name is Hogehoge (a_bcd) Fugafuga"

As mentioned above, I want to create a process that "removes unnecessary characters from the character string in ()".
I considered gsub and replace, but I can't think of a way to replace the string in ().
I would appreciate it if anyone could teach me.

  • Answer # 1

    ()of()Is not a half-width space, half-width alphanumeric characters, or underscore, so if you want to delete it

    str ='My name is Hogehoge (a_bcd) Fugafuga'
    str.sub! (/ \ A ([^ ()] *) ((. *)) ([^ ()] *) \ Z /) {| s | "# $1 (# {$2.delete (" ^) a-zA-Z0-9_ ")}) # $3"}
    puts str

  • Answer # 2

    I enjoyed it for a while, but my regular expression wasn't enough at once.
    a ='My name is Hogehoge (a a_bcd) Fugafuga' b = a.match (/ ([^ (] * () ([^)] *) (). *) /) b [1] + b [2] .gsub (/ [^-~] /, "") + b [3]

Related articles