Sometimes it's useful, sometimes it isn't.
In my regex class, I have an example that is a complete
tokenizer for a calculator program, in one regex.
The calculator accepts
integer and floating-point numerals,
+,
-,
*,
/,
^,
and
** operators,
= for equality,
:= for assignment, parentheses for
operator grouping, and variable names. The
tokenizer is simple and easy to read:
sub tokens {
my @tokens =
split m{ (
\*\* | := # ** or := operator
|
[-+*/^()=] # some other operator
|
[A-Za-z]\w+ # Identifier
|
\d*\.\d+(?:[Ee]\d+)? # Decimal number
|
\d+ # Integer
)
},
shift();
return grep /\S/, @tokens;
}
(To see what this does, pass it a string like
(Foo := 12) + 37^2-42*bar.)
Now what would this look like without /x?
It would be a lot harder to understand:
sub tokens {
my @tokens =
split m{(\*\*|:=|[-+*/^()=]|[A-Za-z]\w+|\d*\.\d+(?:[Ee]\d+)?|\d+)|\s
++},
shift();
return grep /\S/, @tokens;
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.