To add a collaborator to this project you will need to use the Relish gem to add the collaborator via a terminal command. Soon you'll be able to also add collaborators here!More about adding a collaborator
Some people, when confronted with a problem, think
"I know, I'll use regular expressions." Now they have two problems.
-- Jamie Zawinski
Don't use regular expressions if you just need plain text search in string:
For simple constructions you can use regexp directly through string index.
match = string[/regexp/] # get content of matched regexp first_group = string[/text(grp)/, 1] # get content of captured group string[/text (grp)/, 1] = 'replace' # string => 'text replace'
Use non-capturing groups when you don't use captured result of parentheses.
/(first|second)/ # bad /(?:first|second)/ # good
Don't use the cryptic Perl-legacy variables denoting last regexp group matches
$2, etc). Use
/(regexp)/ =~ string ... # bad process $1 # good process Regexp.last_match
Avoid using numbered groups as it can be hard to track what they contain. Named groups
can be used instead.
# bad /(regexp)/ =~ string ... process Regexp.last_match # good /(?<meaningful_var>regexp)/ =~ string ... process meaningful_var
Character classes have only a few special characters you should care about:
], so don't escape
.or brackets in
Be careful with
$as they match start/end of line, not string endings.
If you want to match the whole string use:
\z(not to be
\Zwhich is the equivalent of
string = "some injection\nusername" string[/^username$/] # matches string[/\Ausername\z/] # doesn't match
xmodifier for complex regexps. This makes them more readable and you
can add some useful comments. Just be careful as spaces are ignored.
regexp = / start # some text \s # white space char (group) # first group (?:alt1|alt2) # some alternation end /x
For complex replacements
gsubcan be used with block or hash.
Last published over 6 years ago by David Kariuki.