|
| 1 | +--- |
| 2 | +layout: recipe |
| 3 | +title: Searching for substrings |
| 4 | +chapter: Regular Expressions |
| 5 | +--- |
| 6 | +## Problem |
| 7 | + |
| 8 | +You need to search for a substring, and return either the starting position of the match or the matching value itself. |
| 9 | + |
| 10 | +## Solution |
| 11 | + |
| 12 | +There are several ways to accomplish this using regular expressions. Some methods are called on a `RegExp` pattern or object and some are called on `String` objects. |
| 13 | + |
| 14 | +### `RegExp` objects |
| 15 | + |
| 16 | +The first way is to call the `test` method on a `RegExp` pattern or object. The `test` method returns a boolean value: |
| 17 | + |
| 18 | +{% highlight coffeescript %} |
| 19 | +match = /sample/.test("Sample text") |
| 20 | +# => false |
| 21 | + |
| 22 | +match = /sample/i.test("Sample text") |
| 23 | +# => true |
| 24 | +{% endhighlight %} |
| 25 | + |
| 26 | +The next way to is to call the `exec` method on a `RegExp` pattern or object. The `exec` method returns an array an array with the match information or `null`: |
| 27 | + |
| 28 | +{% highlight coffeescript %} |
| 29 | +match = /s(amp)le/i.exec "Sample text" |
| 30 | +# => [ 'Sample', 'amp', index: 0, input: 'Sample text' ] |
| 31 | + |
| 32 | +match = /s(amp)le/.exec "Sample text" |
| 33 | +# => null |
| 34 | +{% endhighlight %} |
| 35 | + |
| 36 | +### `String` objects |
| 37 | + |
| 38 | +The `match` method matches a given string with the `RegExp`. With 'g' flag returns an array containing the matches, without 'g' flag returns just the first match or if no match is found returns `null`. |
| 39 | + |
| 40 | +{% highlight coffeescript %} |
| 41 | +"Watch out for the rock!".match(/r?or?/g) |
| 42 | +# => [ 'o', 'or', 'ro' ] |
| 43 | + |
| 44 | +"Watch out for the rock!".match(/r?or?/) |
| 45 | +# => [ 'o', index: 6, input: 'Watch out for the rock!' ] |
| 46 | + |
| 47 | +"Watch out for the rock!".match(/ror/) |
| 48 | +# => null |
| 49 | +{% endhighlight %} |
| 50 | + |
| 51 | +The `search` method matches `RegExp` with string and returns the index of the beginning of the match if found, -1 if not. |
| 52 | + |
| 53 | +{% highlight coffeescript %} |
| 54 | +"Watch out for the rock!".search /for/ |
| 55 | +# => 10 |
| 56 | + |
| 57 | +"Watch out for the rock!".search /rof/ |
| 58 | +# => -1 |
| 59 | +{% endhighlight %} |
| 60 | + |
| 61 | +## Discussion |
| 62 | + |
| 63 | +Regular Expressions are a powerful way to test and match substrings. |
0 commit comments