删除非字符比gsub更短的方法(/ \ d | \ W /,“”)

时间:2023-01-06 11:11:46
my_string = 'Here's the #: 49848! - but will dashes, commas & stars (*) show?'

puts src.gsub(/\d|\W/, "")

i.e. can I remove the or ("|").

即我可以删除或(“|”)。

Here's how I got here, can I get shorter?

这是我如何到达这里,我可以变短吗?

src =  "Here's the #: 49848! - but will dashes, commas & stars (*) show?"
puts "A) - " + src
puts "B) - " + src.gsub(/\d\s?/, "")
puts "C) - " + src.gsub(/\W\s?/, "")
puts "D) - " + src.gsub(/\d|\W\s?/, "")
puts "E) - " + src.gsub(/\d|\W/, "")
puts "F) - " + src

A) - Here's the #: 49848! - but will dashes, commas & stars (*) show?
B) - Here's the #: ! - but will dashes, commas & stars (*) show?
C) - Heresthe49848butwilldashescommasstarsshow
D) - Heresthebutwilldashescommasstarsshow
E) - Heresthebutwilldashescommasstarsshow
F) - Here's the #: 49848! - but will dashes, commas & stars (*) show?

n.d. D) and E) are what I want for output. Just characters.

日期不详D)和E)是我想要输出的东西。只是人物。

3 个解决方案

#1


15  

my_string = "Here's the #: 49848! - but will dashes, commas & stars (*) show?"
p my_string.delete('^a-zA-Z')
#=>"Heresthebutwilldashescommasstarsshow"

#2


4  

I have this one

我有这个

src.gsub(/[^a-z]/i, "")

also not shorter, but better to read in my opinion.

也不短,但在我看来更好阅读。

The i modifier makes the regex case independent, so that a-z matches also A-Z. A small difference is that this regex will also replace _ which is not replaced by yours.

i修饰符使正则表达式独立,因此a-z也匹配A-Z。一个小的区别是这个正则表达式也将取代_而不是由你的。

#3


2  

If you want to keep also unicode letters, use this one:

如果你想保留unicode字母,请使用以下字母:

/\PL/

This matches all non letter character.

这匹配所有非字母字符。

#1


15  

my_string = "Here's the #: 49848! - but will dashes, commas & stars (*) show?"
p my_string.delete('^a-zA-Z')
#=>"Heresthebutwilldashescommasstarsshow"

#2


4  

I have this one

我有这个

src.gsub(/[^a-z]/i, "")

also not shorter, but better to read in my opinion.

也不短,但在我看来更好阅读。

The i modifier makes the regex case independent, so that a-z matches also A-Z. A small difference is that this regex will also replace _ which is not replaced by yours.

i修饰符使正则表达式独立,因此a-z也匹配A-Z。一个小的区别是这个正则表达式也将取代_而不是由你的。

#3


2  

If you want to keep also unicode letters, use this one:

如果你想保留unicode字母,请使用以下字母:

/\PL/

This matches all non letter character.

这匹配所有非字母字符。