On the use of regular expressions in Ruby _ruby special topic

Source: Internet
Author: User


If you just need to find the text of the string, do not use regular expressions: string[' text '

For simple structures, you can query directly using the string[/re/] approach.

  Match = string[/regexp/]       # Get content of matched regexp
  first_group = string[/text (GRP)/, 1] # get content of Cap tured Group
  String[/text (GRP)/, 1] = ' Replace ' # string => ' text replace '

When you don't need to group results, use groups that are not grouped.

  /(First|second)/  # bad
  /(?: First|second)/# Good

Do not use Perl legacy variables to represent matching regular groupings (such as $1,$2, etc.), using regexp.last_match[n] as an alternative.

  /(RegExp)/=~ string
  ...

  # bad
  process

  # good
  process regexp.last_match[1]

It's hard to understand what they mean by avoiding the use of digital naming groups. Named groups to override.

  # Bad
  /(regexp)/=~ string
  ...
  Process regexp.last_match[1]

  # good
  /(? <meaningful_var>regexp)/=~ string
  ...
  Process Meaningful_var

The character class has the following special keywords to note: ^,-, \,], so, do not escape. or parentheses in the [].

Note that ^ and $, they match the beginning and end of the line, not the ending of a string, if you want to match the entire string, with \a and \z.

  String = "Some Injection\nusername"
  string[/^username$/]  # matches
  string[/\ausername\z/] # don ' t Match

For complex regular expressions, use an x modifier. You can improve readability and add useful annotations. Just be aware that whitespace characters are ignored.

  RegExp =%r{
   start     # some text
   \s      # white space char
   (group)    # a
   (?: alt1| ALT2) # Some alternation
   end
  }x

Sub/gsub also supports hashing and code block formal syntax, which can be used in complex case substitution operations.

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.