比 gsub(/\d|\W/, "") 更短的删除非字符的方法
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) 是我想要的输出。只是字符。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的这一篇
也不短,但在我看来更好读。
i
修饰符使正则表达式独立于大小写,因此az
也匹配AZ
。一个小小的区别是,这个正则表达式还将替换_
,而它没有被您的正则表达式替换。I have this one
also not shorter, but better to read in my opinion.
The
i
modifier makes the regex case independent, so thata-z
matches alsoA-Z
. A small difference is that this regex will also replace_
which is not replaced by yours.如果您还想保留 unicode 字母,请使用这个:
这会匹配所有非字母字符。
If you want to keep also unicode letters, use this one:
This matches all non letter character.