Using Regular Expressions

Sometimes you want the flexibility of strings, but you need to process them efficiently. Searching and replacing inside of strings can also use a lot of processing cycles. Regular expressions, or regexes, can reduce the costs of string processing substantially thanks to highly optimized processing models. Crystal uses the PCRE syntax.[30] This is implemented as a C binding to the PCRE C-library. (Though Ruby uses a different regex engine, it also uses PCRE syntax.)

Patterns are usually created with the /pattern/ literal syntax. If you have a regex that includes a slash you don’t want to have to escape, you can also create a pattern with %r(pattern). Once you have a pattern, you can apply it to strings. Use =~ or the match method to check whether two strings match and from which starting position.

 str = ​"carbonantimonygolddiamond"
 pattern = ​/gold/
 p str =~ pattern ​# => 14

In this case, gold appeared at starting position 14. If gold wasn’t in the string, the match would have returned nil. Because nil is falsy, this makes it easy to test for matches with if materials =~ pattern, doing some tasks if there is a match and others if there isn’t a match.

You can also extract more information about the string and its relationship to your regex:

 materials = ​"carbonantimonygolddiamond"
 pat = ​/(.+)gold(.+)/​ ​# searches for gold
 
 str = ​"carbonantimonygolddiamond"
 str =~ pat ​# => 0
 $1 ​# => "carbonantimony"
 $2 ​# => "diamond"
 
 str.​match​ pat ​# =>
 # <Regex::MatchData "carbonantimonygolddiamond"
 # 1:"carbonantimony" 2:"diamond">

In this example, the starting position is reported as 0 (also truthy, which is useful for if) because we allowed for a prefix with (.+). The methods from the Regex class let you look deeper into the match results.

Crystal lets you use string interpolation syntax (#{}) in regular expression literals, giving you potentially powerful opportunities at runtime. This also, of course, lets you create runtime exceptions if you interpolate bad syntax, so be careful!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.246.148