background preloader

Ruby Regular Expressions

Ruby Regular Expressions
A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings using a specialized syntax held in a pattern. A regular expression literal is a pattern between slashes or between arbitrary delimiters followed by %r as follows: Syntax: /pattern//pattern/im # option can be specified%r!/usr/local! # general delimited regular expression Example: #! This will produce the following result: Line1 contains Cats Regular-expression modifiers: Regular expression literals may include an optional modifier to control various aspects of matching. Like string literals delimited with %Q, Ruby allows you to begin your regular expressions with %r followed by a delimiter of your choice. # Following matches a single slash character, no escape required%r|/| # Flag characters are allowed with this syntax, too%r[</(.*)>]i Regular-expression patterns: Except for control characters, (+ ? Following table lists the regular expression syntax that is available in Ruby. #!

ruby - Regex, how to match multiple lines Regexp A Regexp holds a regular expression, used to match a pattern against strings. Regexps are created using the /.../ and %r{...} literals, and by the Regexp::new constructor. Regular expressions (regexps) are patterns which describe the contents of a string. A regexp is usually delimited with forward slashes (/). /hay/ =~ 'haystack' /y/.match('haystack') If a string contains the pattern it is said to match. /needle/.match('haystack') /hay/.match('haystack') Specifically, /st/ requires that the string contains the letter s followed by the letter t, so it matches haystack, also. The following are metacharacters (, ), [, ], {, }, ., ? /1 \+ 2 = 3\? Patterns behave like double-quoted strings so can contain the same backslash escapes. /\s\u{6771 4eac 90fd}/.match("Go to 東京都") Arbitrary Ruby expressions can be embedded into patterns with the #{...} construct. place = "東京都"/#{place}/.match("Go to 東京都") Character Classes¶ ↑ /W[aeiou]rd/.match("Word") /[0-9a-f]/.match('9f') /[9f]/.match('9f') Repetition¶ ↑ /(?

Ruby Regular Expressions Finding the first match String.=~(Regexp) returns the starting position of the first match or nil if no match was found: >> "123 456 789" =~ /\d+/=> 0 >> "abc def ghi" =~ /\d+/=> nil >> "found" if "123 456 789" =~ /\d+/=> "found" Special $ variables will contain information about the last match: >> "123 456 789" =~ /\d\d\d/=> 0 # $` contains text before last match# $& contains last matched string# $' contains text after last match>> $` + '[' + $& + ']' + $'=> "[123] 456 789" Accessing captures $n contains the n-th (...) capture of the last match, $~ contains MatchData object: >> "123 456 789" =~ /(\d\d)(\d)/ >> [$1, $2]=> ["12", "3"] >> $~.captures=> ["12", "3"] Finding all matches String.scan returns all matches as String array: String.scan can also be used with a block: Replacing matches String.gsub returns a new String with matches replaced, String.gsub! Modifiers /. Regular expressions by example /a/ character 'a' /\// character '/' (/\? More Information

Is assignment in a conditional clause good ruby style Regular Expressions - A Gentle User Guide and Tutorial A Regular Expression is the term used to describe a codified method of searching invented, or defined, by the American mathematician Stephen Kleene. The syntax (language format) described on this page is compliant with extended regular expressions (EREs) defined in IEEE POSIX 1003.2 (Section 2.8). EREs are now commonly supported by Apache, PERL, PHP4, Javascript 1.3+, MS Visual Studio, most visual editors, vi, emac, the GNU family of tools (including grep, awk and sed) as well as many others. Extended Regular Expressions (EREs) will support Basic Regular Expressions (BREs are essentially a subset of EREs). Most applications, utilities and laguages that implement RE's, especially PERL, extend the ERE capabilities and what are typically called PERL Compatible Regular Expressions (PCREs) have, largely, become a de facto standard. Implementation documentation should always be consulted in case some wierd Regular Expression variant is involved. Contents The title is deceptive. Simple Matching

Ruby Regex Examples | LZone This post gives some simple examples for using regular expressions in Ruby scripts. 1. Syntax Compared to other scripting languages Ruby more behaves like Perl allowing to use regex seemlessly without the need for explicit objects in Python or a function in PHP. 2. Here are some syntax examples that check strings for certain content: Basic Matching Using different regex delimiters Changing the delimiter becomes useful in some cases Case sensitity Matching with wildcards Using quantifiers Replacing Patterns You need to do substitution using the in place string object methods sub! Extracting Data with Ruby Regex To extract data using regular expression we have to use capture/grouping syntax and to do exactly one match: the String#match method and MatchData#captures to produce a result arrayto do multiple matches: the String#scan method which returns a nested array with an result array for each match Some basic examples to do the exactly one match with String#match

How to use rails-i18n with HAML regex - Regular Expressions: Is there an AND operator scan (String scan(p1)public Both forms iterate through str, matching the pattern (which may be a Regexp or a String). For each match, a result is generated and either added to the result array or passed to the block. If the pattern contains no groups, each individual result consists of the matched string, $&. If the pattern contains groups, each individual result is itself an array containing one entry per group. a = "cruel world"a.scan(/\w+/) a.scan(/.../) a.scan(/(...)/) a.scan(/(..)(..)/) And the block form: a.scan(/\w+/) {|w| print "<<#{w}>> " }print "\n"a.scan(/(.)(.)/) {|x,y| print y, x }print "\n" produces: <<cruel>><<world>> rceu lowlr Show source static VALUErb_str_scan(VALUE str, VALUE pat){ VALUE result; long start = 0; long last = -1, prev = 0; char *p = RSTRING_PTR(str); long len = RSTRING_LEN(str); pat = get_pat(pat, 1); if (!

WebSockets on Rails 4 and Ruby 2 - Pogoapp WebSockets are an exciting new HTML5 technology which has finally begun to pick up enough browser, server and library support to see much wider adoption, potentially driving a move towards a signficantly new kind/kinds of web client/server communication. We've been making use of websockets with socket.io and node.js, but good old Rails doesn't need to be left out. We're going to use Dan Knox's slick high-level websocket-rails gem, and actually copy/port over a good bit of code from the slightly outdated example project. But why stop with WebSockets? That even means we can skip the step of removing Rack::Lock, because Rails 4 is threadsafe by default. Setup So first we'll install Ruby 2, Rails 4, and setup a new project (this assumes you're using rbenv, YMMV): rbenv install 2.0.0-p247export RBENV_VERSION=2.0.0-p247gem install rails --version 4.0.0 --no-ri --no-rdocrails new ws42 Then just add to the Gemfile: ruby '2.0.0'gem 'websocket-rails' And install: Code The core of which looks like this:

ruby on rails - Determine if a string is a valid float value

Related: