简体   繁体   English

Ruby Regex Gsub何时不匹配

[英]Ruby Regex Gsub when does not match

I want to gsub all characters in a string that are not letters and replace with '#'. 我想在字符串中gsub所有不是字母的字符,并用'#'替换。 I think I need a regular expression that goes something like, "gsub() when this regex does not match." 我想我需要一个正则表达式,就像这个正则表达式不匹配时的“gsub()”。

Any ideas? 有任何想法吗?

看马,没有正则表达式......

str.tr( '^A-Za-z', '#' )
str.gsub(/[^a-zA-Z]/, '#')

^表示不匹配

当然,你可以使用字符类否定:

"aBc$%^".gsub(/[^A-Za-z]/, '#') => "aBc###"

在Codepad上试试这个

puts "kjhdfuy37685682#$$%@dfjahf".gsub(/[^a-z]/i, '#')

Words do count 言语确实很重要

all character s ... replace with '#' str.gsub(/[^a-zA-Z]+/, '#') 所有字母S ...以'#'取代str.gsub(/[^a-zA-Z]+/, '#')

each character ... replace with '#' str.gsub(/[^a-zA-Z]/, '#') 每个字符......替换为'#' str.gsub(/[^a-zA-Z]/, '#')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM