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. #!

[Akita Responde] Começando com Ruby on Rails Agora, para começar a entender a teoria, existem alguns materiais que você pode usar: Se estiver muito no começo de programação em geral, leia o livro Aprenda a Programar, do Chris Pine, traduzido em português. Se quiser aprender a linguagem Ruby, leia o livro O Guia (Comovente) de Ruby do Why, também traduzido em português. Os seguintes livros são interessantes para Ruby: The Ruby Way, do Hal Fulton, é um dos melhores livros para aprender Ruby a fundo. Aliás, um cuidado importante: se você veio de outra linguagem, vai querer programar Ruby do jeito Java, ou do jeito PHP, mas assim você está fazendo errado. Para aprender Ruby on Rails, o framework Web, veja estas referências: O site oficial tem o Rails Guides com uma documentação completa de tudo que você precisa para começar no Ruby on Rails. Não recomendo comprar livros muitos avançados de Rails, porque o framework está evoluindo o tempo todo e os livros impressos de Rails tendem a ficar obsoletos muito rápido.

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

21 Ruby Tricks You Should Be Using In Your Own Code Writing for Ruby Inside, I get to see a lot of Ruby code. Most is good, but sometimes we forget some of Ruby's shortcuts and tricks and reinvent the wheel instead. In this post I present 21 different Ruby "tricks," from those that most experienced developers use every day to the more obscure. Whatever your level, a refresh may help you the next time you encounter certain coding scenarios. Note to beginners: If you're still learning Ruby, check out my Beginning Ruby book. 2009 Update: This post was written in early 2008 and looking back on it, there are a couple of tricks that I wouldn't recommend anymore - or to which extra warnings need to be added. 1 - Extract regular expression matches quickly A typical way to extract data from text using a regular expression is to use the match method. email = "Fred Bloggs <>"email.match(/<(.*?) Ultimately, using the String#[] approach is cleaner though it might seem more "magic" to you. x = 'this is a test' x[/[aeiou].+? puts x == 10 ?

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

Ruby Procs And Lambdas (And The Difference Between Them) As you know, I am a big believer in knowing the basics. I find it is especially valuable to go back to the fundamentals of whatever skill you're trying to master periodically, as you gain more experience. Somehow you're always able to extract something valuable from the experience due to the extra insight you've acquired along the way. Recently I've been looking more closely at some Ruby concepts that I may have glossed over when I was learning the language initially, so I will likely be writing about this in some of my upcoming posts. What's So Good About Procs? You know how everything in Ruby is an object, well, as it turns out that's not quite true. Procs And Lambdas In Detail There are three ways to create a Proc object in Ruby. Using Those are all the different ways to get a Proc object in Ruby (either a proc or a lambda). Procs Are First Class (Functions That Is) alan@alan-ubuntu-vm:~/tmp$ ruby a.rb String are equal? alan@alan-ubuntu-vm:~/tmp$ ruby a.rb Procs are equal?

How to use rails-i18n with HAML regex - Regular Expressions: Is there an AND operator