What are good regular expressions? *

Question

I have worked for 5 years mainly in java desktop applications accessing Oracle databases and I have never used regular expressions. Now I enter Stack Overflow and I see a lot of questions about them; I feel like I missed something.

For what do you use regular expressions?

P.S. sorry for my bad english

Answer

Consider an example in Ruby:

puts "Matched!" unless /\d{3}-\d{4}/.match("555-1234").nil?
puts "Didn't match!" if /\d{3}-\d{4}/.match("Not phone number").nil?

The "/\d{3}-\d{4}/" is the regular expression, and as you can see it is a VERY concise way of finding a match in a string.

Furthermore, using groups you can extract information, as such:

match = /([^@]*)@(.*)/.match("myaddress@domain.com")
name = match[1]
domain = match[2]

Here, the parenthesis in the regular expression mark a capturing group, so you can see exactly WHAT the data is that you matched, so you can do further processing.

This is just the tip of the iceberg... there are many many different things you can do in a regular expression that makes processing text REALLY easy.

< br > via < a class="StackLink" href=" http://stackoverflow.com/questions/4954/" >What are good regular expressions?< /a>
Share on Google Plus

About Cinema Guy

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment