iaacp
iaacp

Reputation: 4855

Finding a specific, simple string with regexes

So I'm new to regular expressions and having difficulty understanding them. To get my feet wet, I've made one that identifies the date with either dashes or slashes. It looks like this:

\d{1,2}[-/]\d{1,2}[-/](\d{4}|\d{2})

I realize it isn't 100% accurate because hypothetically it would accept 32-96-2012 as the date but that's fine. This isn't for homework or work so it doesn't need to be, I just want to understand simple regexes.

So now I'd like to understand how to search for a specific word, and I'm quite confused. For example, if I wanted to search a text document for the word "soap", or "Tom". If anyone could post a simple example and description, I'd appreciate it!

Upvotes: 0

Views: 64

Answers (2)

Neil
Neil

Reputation: 5780

Regular expressions are made to be as readable as possible (believe it or not). So if I wanted to search for a text document with the word soap, the regular expression is "soap".

If I wanted soap or Tom, then it becomes (?:soap|Tom). The (?:) enclosure means to treat the contents of the (?:) enclosure as its on mini regular expression. The | character is an or operator, meaning whatever's to the left or whatever to the right. So with that, (?:soap|Tom) means to find the word soap or the word Tom.

Why couldn't I have written soap|Tom instead? If I wanted to look for "soap box" or "Tom box", then soap|Tom box would not work. This would match soap or Tom box, but not soap box.

It's definitely confusing at first, but you learn to look for groupings and take it apart piece by piece to know what it's really looking for.

Upvotes: 1

Sibster
Sibster

Reputation: 3189

a simple /soap/ or /Tom/ would do it.
more info http://www.codeproject.com/Articles/9099/The-30-Minute-Regex-Tutorial

Upvotes: 2

Related Questions