by shittyanalogy · 12y ago · 0 comments
Read the wikipedia page which has a great description of what regular expressions are and why you would use them: https://en.wikipedia.org/wiki/Regular_expression
Read the JS docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guid...
Test your regexes: http://regexpal.com/
Visualize your regexes: http://www.regexper.com/
Try some challenges: http://callumacrae.github.io/regex-tuesday/
And remember, writing regular expressions can be very difficult, reasoning about your regular expressions can be even more so, defining your problem can be the most difficult of all. Think before you regex.
Sadly, the only one that does is perl6.
For example, using C, file-local, pre-processor:
#define MATCH_NAME_RE "[a-zA-Z]+"
#define MATCH_SPACES_RE "\s+"
#define CAPTURE_NUMBER_RE "(\d+\)"
And then:
re = QRegex( MATCH_NAME_RE MATCH_SPACES_RE CAPTURE_NUMBER_RE );
It both documents what each part does, makes it easier to debug and change them later on and makes them grokable. It only breaks down when you're doing very complex matching, but most of the time RE can be broken into smaller pieces. a = re.compile(r"""\d + # the integral part
\. # the decimal point
\d * # some fractional digits""", re.X) OPERATOR = /// ^ (
?: [-=]> # function
| [-+*/%<>&|^!?=]= # compound assign / compare
| >>>=? # zero-fill right shift
| ([-+:])\1 # doubles
| ([&|<>])\2=? # logic / shift
| \?\. # soak access
| \.{2,3} # range or splat
) ///
When turned into Javascript it becomes: var OPERATOR;
OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3})/;I had a look through the regex tuesday list. It looks like fun for people who know their way around regexs but if you're just learning I'd recommend starting with something simpler.
These look like a more reasonable starting level : http://regexone.com/
It goes into more detail about some things that were glossed over in the OP, which may be overwhelming for a newbie but necessary for advancing.