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. #! Related:  Ruby Tuts:

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: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial Regular expressions, though cryptic, is a powerful tool for working with text. Ruby has this feature built-in. It's used for pattern-matching and text processing. Many people find regular expressions difficult to use, difficult to read, un-maintainable, and ultimately counterproductive. A regular expression is simply a way of specifying a pattern of characters to be matched in a string. You could write a pattern that matches a string containing the text Pune or the text Ruby using the following regular expression: The forward slashes delimit the pattern, which consists of the two things we are matching, separated by a pipe character (|). The simplest way to find out whether there's a match between a pattern and a string is with the match method. m1 = /Ruby/.match("The future is Ruby") puts m1.class m2 = "The future is Ruby" =~ /Ruby/ puts m2 m1 = /Ruby/.match("The future is Ruby") puts m1.class # it returns MatchData m2 = "The future is Ruby" =~ /Ruby/ puts m2 # it returns 14

Ruby for Newbies: Regular Expressions Ruby is a one of the most popular languages used on the web. We’ve started a new Session here on Nettuts+ that will introduce you to Ruby, as well as the great frameworks and tools that go along with Ruby development. In this lesson, we’ll look at using regular expression in Ruby. If you’re familiar with regular expressions, you’ll be glad to know that most of the syntax for writing the actual regular expressions is very similar to what you know from PHP, JavaScript, or [your language here]. If you’re not familiar with regular expressions, you’ll want to check out our Regex tutorials here on Nettuts+ to get up to speed. Just like everything else in Ruby, regular expressions are regular objects: they’re instances of the Regexp class. To start, the simplest way to use a regexp is to apply it to a string and see if there’s a match. Both of these examples match, and so we’re going to get a MatchData instance back (we’ll look at MatchData objects soon). So, let’s execute this: subsub!

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

UT on Rails Last year I held a series of non credit Rails courses for University of Texas Students, i’m happy to announce that i’ve been granted an Adjunct Professor position at the UT and I’m teaching a for credit course in Databases and Rails. Lucky for you, i’m a sucker for online learning, so i’ll be putting all my course material online, right here. The Course This Ruby on Rails course is 10 weeks long and assumes you know very little about programming and have not used Ruby, Rails, or Databases previously. I’m taking a fairly non traditional approach to teaching Rails, so even if you’ve been coding for a year or so, you’ll still likely get something out of the course, especially the exercises. Week 1: Introduction to Databases This first week we focus on databases and won’t get into Rails until the second week. The first part of this lecture covers the format and content of the course, why we use databases, and how the web is structured around data and data storage. More Exercise: More More More

Regex Runner: a game to teach regular expressions to kids Last December, I wrote a column suggesting that games would be a great way to teach kids Regular Expressions, a part of the world of programming that surfaces in tons of non-expert applications, like word processors. Now, Sal writes, "For my Computer Games course project, I used your article regarding reg-exp to try to make an educational game, there's already SO many academic papers and books on this area it's overwhelming. Rather than read up and design something based on researched principles, I thought instead about what game I was playing most on my phone and I decided those "always running" type games (Temple Run/Canabalt etc) are super cool. Using that mechanic as a template, I shoehorned in some letters and symbols and played around with a randomly generated grid and a couple of sprites. Regex Runner

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