When using gsub with [a-zA-Z] in ruby

时间:2017-03-22 18:48:42

标签: ruby regex gsub

I've seen this [a-zA-Z] for the gsub method:

string.gsub(/[a-zA-Z]/,"-")

where it will find any lower case letters a-z and or uppercase letters A-Z.

My question is why does this a-z work back to back with A-Z : a-zA-Z ?

Where might I find more info on using [a-zA-Z] in ruby?

3 个答案:

答案 0 :(得分:1)

character class(正则表达式中的[])内,您可以列出您想要的所有字符:

/[abcdefg]/

要获得一些空间,您可以使用连字符(-)定义一个范围,并在-的每一侧定义一个字母:

/[a-g]/

由于很清楚此范围是从ag,您可以在以下后直接编写另一个字符:

/[a-gm]/

您还可以定义另一个范围:

/[a-gm-z]/

来自documentation

  

范围可以跟随另一个范围,因此[abcdwxyz]是等价的   至[a-dw-z]

请注意,对于您的示例,您还可以使用不区分大小写的正则表达式:

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

最后,您可以使用unicode characters范围:

arrows = /[\u2190-\u21FF]/
"a⇸b⇙c↺d↣e↝f".scan(arrows)
# => ["⇸", "⇙", "↺", "↣", "↝"]

答案 1 :(得分:0)

  

字符类用方括号([,])分隔,并列出可能出现在匹配中该点的字符。 / [ab] /表示a或b,而不是/ ab /表示a后跟b。

/W[aeiou]rd/.match("Word") #=> #<MatchData "Word">
  

在字符类中,连字符( - )是表示字符的元字符   包含范围的字符。 [abcd]相当于[a-d]。范围   可以跟着另一个范围,所以[abcdwxyz]相当于   [A-DW-Z]。范围或单个字符出现的顺序   在一个角色类里面是无关紧要的。

/[0-9a-f]/.match('9f') #=> #<MatchData "9">
/[9f]/.match('9f')     #=> #<MatchData "9">

Worth looking into ruby's doc for more details.

答案 2 :(得分:0)

我经常使用http://rubular.com/作为参考

  

[a-zA-Z] a-z或A-Z

范围内的任何单个字符