[英]Ruby - regular expression
str1 = "M Rahim (C)(W): 61(97)S A Hasan: 51(68)"
str2 = "R Taylor (C): 76(160)B Watling: 16(26)"
puts format(str1) #=> "M Rahim (C)(W): 61(97)\nS A Hasan: 51(68)"
puts format(str2) #=> "R Taylor (C): 76(160)\nB Watling: 16(26)"
for getting these output what I need to do in format()
function. 为了获得这些输出,我需要在
format()
函数中执行的操作。 I am not much familiar with regular expressions 我对正则表达式不太熟悉
This might do the trick but it is hard to know with such a limited sample: 这也许可以解决问题,但很难通过如此有限的示例来了解:
def format(s)
s.sub(/\A(.*?:\s*\d+\(\d+\))/) { $1 + "\n" }
end
The main thing that looks for is ': 61(97)'
and ': 76(160)'
or, generally, a colon followed by zero or more whitespace characters followed by a number followed by a number within parentheses. 查找的主要内容是
': 61(97)'
和': 76(160)'
或者通常是一个冒号,后跟零个或多个空格字符,后跟一个数字,然后在括号内加上一个数字。
If you don't know how many entries are on each line then you can use scan
to extract them and join
to put them back together: 如果你不知道有多少项是在每一行,那么你可以使用
scan
提取它们,并join
把他们重新走到一起:
def format(s)
s.scan(/.*?:\s*\d+\(\d+\)/).join("\n")
end
for example: 例如:
>> s = str1 + str2
=> "M Rahim (C)(W): 61(97)S A Hasan: 51(68)R Taylor (C): 76(160)B Watling: 16(26)"
>> s.scan(/.*?:\s*\d+\(\d+\)/).join("\n")
=> "M Rahim (C)(W): 61(97)\nS A Hasan: 51(68)\nR Taylor (C): 76(160)\nB Watling: 16(26)"
Well here is a method that finds any )
followed by a capital letter and inserts a newline after the )
: 好吧,这里是一个找到
)
后跟大写字母并在)
之后插入换行符的方法:
def format(s)
s.gsub(/\)(?=[A-Z])/, ")\n")
end
The /
starts the regular expression. /
开始正则表达式。
The \\)
matches any right parenthesis in the string. \\)
匹配字符串中的任何右括号。 The slash is needed because )
has a special meaning in regular expressions, so it needs to be escaped. 需要使用斜杠,因为
)
在正则表达式中具有特殊含义,因此需要转义。
The (?=[AZ])
is a positive lookahead assertion, asserting the the parenthesis is followed by a capital letter. (?=[AZ])
是一个正向超前断言,断言括号后跟一个大写字母。
The second /
ends the regular expression. 第二个
/
结束正则表达式。
def format(string)
string.sub(/(\d\))/, '\1' + "\n")
end
p format("M Rahim (C)(W): 61(97)S A Hasan: 51(68)") #=> "M Rahim (C)(W): 61(97)\nS A Hasan: 51(68)"
p format("R Taylor (C): 76(160)B Watling: 16(26)") #=> "R Taylor (C): 76(160)\nB Watling: 16(26)"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.