Send Close Add comments: (status displays here)
Got it!  This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
Regular expressions and printf


1. Regular expressions and printf

2. Regular expressions and printf
Regular expressions can be used to pick apart a printf string for further processing. Here is an example in C. For more examples, see Printf strings .

Here is the C code.

Here is the output of the C code.


3. Text string
The text string being used is the following.
"The sum of %d and %d is %d."

The goal is to use regular expressions to pick apart the text and format string parts into lists.

4. Parts of a string
Here are the characters in the string. Regular expressions match characters. Blanks are important so any blanks in a pattern need to be matched in the string being matched.

Here is the JavaScript code.

Here is the output of the JavaScript code.


5. Regular expression matches
A common way to find multiple patterns in a string using a regular expression, where further processing is desired, is to match a prefix, the pattern, a suffix, and then do further matching on the suffix, saving intermediate results as needed.

6. One pattern
Here is the JavaScript code.

Here is the output of the JavaScript code.

The problem here is that the last match is found, not the first match.

7. Lazy and greedy matches
A greedy (or eager) match attempts to match as much of the text as possible (i.e., to the last match).

A lazy match stop as soon as possible (i.e., at the first match).

In the above case, a greedy match found the last match but ignored the others. In this case, a lazy match is needed.

The ".*" pattern matches in a greedy (eager) way.

The ".*?" pattern matches in a lazy way. That is, with the question mark "?" following the asterisk "*".

8. Lazy match
Here is the JavaScript code.

Here is the output of the JavaScript code.


9. Find all matches
Some languages have ways to help find multiple matches. But the following way works in any language (that has the regular expression pattern matching).

... to be added , as done in class ...

10. End of page