What are good regular expressions?

后端 未结 9 1054
我寻月下人不归
我寻月下人不归 2021-02-08 05:00

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

9条回答
  •  萌比男神i
    2021-02-08 05:22

    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.

提交回复
热议问题