Regular Expression Examples

Generally, RegularExpressions are defined in terms of whether a string matches the given RegularExpression, although much more complex variants are certainly in widespread use.

Simple examples:
Here are some more: -- RaphLevien


RegXy

Another example, as in a beer program in RegXy, which is an programming language (EsotericProgrammingLanguage) with only 2 things, RegularExpressions and if/goto commands: Syntax: Query: LABEL/expr/JUMP_TARGET_ON_MATCH

Change: LABEL/expr/SUBSTITUTE/

(Do you see how simple this is?)


Example usage of RegularExpressions in Validation

I have had great success using RegularExpressions in validation routines. They're perfectly suited for those ever changing user requirements like "We can't permit commas, periods or ampersands in field X. The field also has to be between 8 and 12 characters, begin with an S and contain another letter at position 6".

Coding this example would give no room for changes, where as a regular expression can be stuck in a database field which can be modified later if necessary. Besides, the code to test the string is much simpler when using a regular expression.

Shhhhhh... you don't want TopMind to see this, do you? :p


A little story from last night's ExtremeProgramming meeting drives home an aspect of RubyLanguage. We had two pairs working, and someone from the other pair called out, "What's the name of the 'string ends with' method?" I called back, "You want regular expression matching. Stick a dollar sign at the end." Well, they pored through the String API docs to discover that there's no built-in method for determining whether a string ends with a given substring. I called out, "Python has such a thing; Ruby does not. Use a regular expression, and stick a dollar sign at the end."

In the meantime, my pair and I needed to test whether a filename ended with a particular extension. If we were working in PythonLanguage we would have written

 fname.endswith('.txt')
This would return True or False. In RubyLanguage we did a RegularExpression match:

 fname =~ /\.txt$/
This returns the index of where the match starts, or nil if there's no match. (In Ruby, nil is false and a number -- even the number 0 -- is true.) We joked that we could write a String#endswith method and sell it to the other pair.

The moral of the story is, RegularExpression handling isn't built in to RubyLanguage just as a convenience; you're actually expected to use regexes, even for common things like an "ends with" test.

-- ElizabethWiethoff
Guides to RegularExpressions
CategoryRegularExpressions

EditText of this page (last edited October 1, 2011) or FindPage with title or text search