DEV Community

sarahnosal
sarahnosal

Posted on

RegEx What?

If you're anything like I was 10 minutes prior to writing this blog- you have little to no understanding of what RegEx do or when to use them. Well lucky for you, you've stumbled upon this article, and I'm here to enlighten you.

RegEx- or regular expressions- are powerful ways to search through strings or blocks of text for particular patterns. Some basic tasks they can be used for are data validation, searching, mass file renaming, and finding records in a database. Think creating emails, usernames, or passwords on a website- there's always requirements like one uppercase character, or a special symbol. Well how do you think the site knows whether or not you've typed in a valid password or email? RegEx.

There are two ways to write RegEx, either between two forward slashes: /your regex/ or the long way by creating a regular expression object: Regexp.new('your regex'). Writing a series of letters or numbers in your RegEx will result in a search for the exact matches of this pattern anywhere in the string that you're searching. However- the only reason to use the plain forward slashes way of writing regex is if you want to find a specific word, or pattern within the string you're searching through. If you would like to search for multiple specific characters, like vowels, you would need to include brackets- /[aeiou]/. This will search the string for every instance of each of those vowels. One cool feature of RegEx is the ability to use ranges, for instance if you want to find every number in your string, rather than writing /[0123456789], you could simply write [0-9], and it would return the same results.

Now you're probably thinking...'okay I know how to write RegEx but how do I incorporate that into Ruby?' Well I got you. There are a few Ruby methods that you can pass your RegEx to and they'll return some different results. First- scan. It will return an array of all items in your string that match a given RegEx. See the example below:

"Duchess is the cutest dog ever".scan(/[aeiou]/)
=> ["u", "e", "i", "e", "u", "e", "o", "e", "e"]
Enter fullscreen mode Exit fullscreen mode

Next is match. It will return the first item in your string that matches the RegEx as a MatchData object. Using Duchess as an example again:

"Duchess is the cutest dog ever".match(/\w+est/)
=> #<MatchData "cutest"> 
Enter fullscreen mode Exit fullscreen mode

A fantastic resource for figuring out more RegEx syntax is Rubular. I know I haven't gone too crazy in depth into this crash course on RegEx, but I hope I've given you enough of a push in the right direction to use this in your own code. Or at least the resources to find out more information and ways to find new patterns. Happy coding!

Discussion (0)