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

发布于 2025-01-02 03:41:46 字数 860 浏览 2 评论 0 原文

my_string = 'Here's the #: 49848! - but will dashes, commas & stars (*) show?'

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

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

我是这样过来的,我可以再短一点吗?

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?

nd D) 和 E) 是我想要的输出。只是字符。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情绪失控 2025-01-09 03:41:46
my_string = "Here's the #: 49848! - but will dashes, commas & stars (*) show?"
p my_string.delete('^a-zA-Z')
#=>"Heresthebutwilldashescommasstarsshow"
my_string = "Here's the #: 49848! - but will dashes, commas & stars (*) show?"
p my_string.delete('^a-zA-Z')
#=>"Heresthebutwilldashescommasstarsshow"
水中月 2025-01-09 03:41:46

我的这一篇

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

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

i 修饰符使正则表达式独立于大小写,因此 az 也匹配 AZ。一个小小的区别是,这个正则表达式还将替换 _ ,而它没有被您的正则表达式替换。

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.

书间行客 2025-01-09 03:41:46

如果您还想保留 unicode 字母,请使用这个:

/\PL/

这会匹配所有非字母字符。

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

/\PL/

This matches all non letter character.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文