Analysis of the use of regular expressions in Ruby, analysis of ruby Regular Expressions

Source: Internet
Author: User
Tags character classes

Analysis of the use of regular expressions in Ruby, analysis of ruby Regular Expressions


If you only need to search for the text of a string, do not use a regular expression: string ['text']

You can use string [/RE/] to query a simple structure.

  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'

When you do not need to group results, use non-group groups.

  /(first|second)/  # bad  /(?:first|second)/ # good

Do not use Perl legacy variables to represent matched regular groups (such as $1, $2, etc.). Use Regexp. last_match [n] as an alternative.

  /(regexp)/ =~ string  ...  # bad  process $1  # good  process Regexp.last_match[1]

It is difficult to understand what they mean by using digital naming groups. Naming groups to replace.

  # bad  /(regexp)/ =~ string  ...  process Regexp.last_match[1]  # good  /(?<meaningful_var>regexp)/ =~ string  ...  process meaningful_var

Character classes have the following special keywords worth noting: ^,-, \,]. Therefore, do not escape. Or brackets in.

Note: ^ and $ match the beginning and end of A line, instead of the end of A string. If you want to match the entire string, use \ A and \ Z.

  string = "some injection\nusername"  string[/^username$/]  # matches  string[/\Ausername\Z/] # don't match

The x modifier is used for complex regular expressions. It can improve readability and add useful comments. Note that the white space characters are ignored.

  regexp = %r{   start     # some text   \s      # white space char   (group)    # first group   (?:alt1|alt2) # some alternation   end  }x

Sub/gsub also supports hash and code block syntax, which can be used for replacement operations in complex situations.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.