Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Which Cases Is Better To Use Regular Expressions?

Tags:

regex

use-case

I'm starting to learn Regular Expressions and I want to know: In which cases is better to use them?

like image 935
Nathan Campos Avatar asked Nov 07 '09 21:11

Nathan Campos


4 Answers

Regular expressions is a form of pattern matching that you can apply on textual content. Take for example the DOS wildcards ? and * which you can use when you're searching for a file . That is a kind of very limited subset of RegExp. For instance, if you want to find all files beginning with "fn", followed by 1 to 4 random characters, and ending with "ht.txt", you can't do that with the usual DOS wildcards. RegExp, on the other hand, could handle that and much more complicated patterns.

Regular expressions are, in short, a way to effectively

  • handle data
  • search and replace strings
  • provide extended string handling.

Often a regular expression can in itself provide string handling that other functionalities such as the built-in string methods and properties can only do if you use them in a complicated function or loop.

like image 188
Nadir SOUALEM Avatar answered Oct 12 '22 11:10

Nadir SOUALEM


When you are trying to find/replace/validate complicated string patterns.

like image 42
Nestor Avatar answered Oct 12 '22 09:10

Nestor


I use regular expressions when comparing strings (preg_match), replacing substrings (sed,preg_replace), replacing characters (sed,preg_replace), searching for strings in files (grep), splitting strings (preg_split) etc.

It is a very flexible and widespread pattern expression language and it is very useful to know.

BUT! It's like they say about poker, it's very easy to learn, but very hard to master.

I just came across a question that i thought was perfect for a RegEx, have a look and decide for yourself.

like image 25
Peter Lindqvist Avatar answered Oct 12 '22 11:10

Peter Lindqvist


There are some cases where, if you need better performance, you should avoid regular expressions in favor of writing code. An example of this is parsing very large CSV files.

like image 41
Robert Harvey Avatar answered Oct 12 '22 09:10

Robert Harvey