Answers:
该g
代表全球,在全球(全部)取代:
在irb中:
>> "hello".sub('l', '*')
=> "he*lo"
>> "hello".gsub('l', '*')
=> "he**o"
replace
和replaceAll
。但是Ruby起源于使用g
修饰符的Perl 。这只是其中之一。
A, sentence, separated, by, commas".gsub!(/(.*),(.*)/,"\\2 \\1") => " commas A, sentence, separated, by"
想法为什么gsub!
似乎只能查找/替换第一个实例?
sub
并gsub
分别替换第一个和所有匹配项。
sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
fixed = FALSE, useBytes = FALSE)
gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
fixed = FALSE, useBytes = FALSE)
sub("4", "8", "An Introduction to R Software Course will be of 4 weeks duration" )
##"An Introduction to R Software Course will be of 8 weeks duration"
gsub("4", "8", "An Introduction to R Software Course will be of 4 weeks duration" )
##"An Introduction to R Software Course will be of 8 weeks duration"