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 Z Wikibooks, biblioteki wolnych podręczników. Ruby to interpretowany, w pełni obiektowy język programowania stworzony przez Yukihiro Matsumoto (pseudonim Matz). W języku angielskim ruby oznacza rubin. Od roku 2003 lawinowo zdobywa nowych zwolenników, głównie za sprawą popularnego frameworku do tworzenia aplikacji webowych o nazwie Ruby on Rails, tworzonego przez grupę programistów pod kierownictwem Davida Heinemeiera Hanssona. W roku 2005 według statystyk sklepu Amazon dwie najpopularniejsze książki na temat Rubiego i Ruby on Rails były najlepiej sprzedawanymi pozycjami z kategorii Programowanie. Punktem wyjścia dla niniejszego podręcznika stała się książka Marka Slagella "Ruby's User Guide" udostępniona na licencji GNU Free Documentation License. Spis treści[edytuj] Podstawy[edytuj] Programowanie zorientowane obiektowo[edytuj] Licencja[edytuj] Licencja Zobacz też[edytuj] Linki zewnętrzne[edytuj]

[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

Ruby Basic Tutorial Troubleshooters.Com, Code Corner and Ruby Revival Present Ruby Basic Tutorial Copyright (C) 2005 by Steve Litt Note: All materials in Ruby Revival are provided AS IS. By reading the materials in Ruby Revival you are agreeing to assume all risks involved in the use of the materials, and you are agreeing to absolve the authors, owners, and anyone else involved with Python Patrol of any responsibility for the outcome of any use of these materials, even in the case of errors and/or omissions in the materials. If you do not agree to this, you must not read these materials. To the 99.9% of you honest readers who take responsibility for your own actions, I'm truly sorry it is necessary to subject all readers to the above disclaimer. CONTENTS This is a Ruby tutorial for one not knowing Ruby. Ruby can be used as a fully object oriented language, in which case you'd create classes and objects to accomplish everything. This is the simplest possible Ruby program, hello.rb. Let's count to 10... Retry

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

Język programowania Ruby