ruby on rails - Why can't regular expressions match for @ sign? -
for string be there @ six.
why work:
str.gsub! /\bsix\b/i, "seven" but trying replace @ sign doesn't match:
str.gsub! /\b@\b/i, "at" escaping doesn't seem work either:
str.gsub! /\b\@\b/i, "at"
this down how \b interpreted. \b "word boundary", wherein zero-length match occurs if \b preceded or followed word character. word characters limited [a-za-z0-9_] , maybe few other things, @ not word character, \b won't match before (and after space). space not boundary.
if need replace @ surrounding whitespace, can capture after \b , use backreferences. captures preceding whitespace \s* zero or more space characters.
str.gsub! /\b(\s*)@(\s*)\b/i, "\\1at\\2" => "be there @ six" or insist upon whitespace, use \s+ instead of \s*.
str = "be there @ six." str.gsub! /\b(\s+)@(\s+)\b/i, "\\1at\\2" => "be there @ six." # no match without whitespace... str = "be there@six." str.gsub! /\b(\s+)@(\s+)\b/i, "\\1at\\2" => nil at point, we're starting introduce redundancies forcing use of \b. done /(\w+\s+)@(\s+\w+)/, foregoing \b match \w word characters followed \s whitespace.
update after comments:
if want treat @ "word" may appear @ beginning or end, or inside bounded whitespace, may use \w match "non-word" characters, combined ^$ anchors "or" pipe |:
# replace @ @ start, middle, before punctuation str = "@ there @ 6 @." str.gsub! /(^|\w+)@(\w+|$)/, '\\1at\\2' => "at there @ 6 at." (^|\w+) matches either ^ start of string, or sequence of non-word characters (like whitespace or punctuation). (\w+|$) similar can match end of string $.
Comments
Post a Comment