Reputation: 4093
I've made a JavaScript regular expression to change instances of vertical-bar-sets for a LaTeX renderer, but when I have multiple such instances within the same paragraph it affects only the very first and very last bars, when I would prefer it to match each set of bars. The regular expression is:
replace(/\|(.*)\|/g, "\\textsc{$1}");
For example, with the following example:
Lorem |ipsum| dolor sit |amet|, consectetur |adipiscing| elit.
my regular expression produces:
Lorem \textsc{ipsum| dolor sit |amet|, consectetur |adipiscing} elit.
But I would prefer that it match all sets to the smallest degree possible, like so;
Lorem \textsc{ipsum} dolor sit \textsc{amet}, consectetur \textsc{adipiscing} elit.
How would I best correct my regular expression to solve this problem?
Upvotes: 0
Views: 131
Reputation: 93000
Another way is to add a single character to your original regex:
replace(/\|(.*?)\|/g, "\\textsc{$1}");
Everyone knows about * and +, but I am surprised how non-popular are their siblings *? and +?. They do the same thing except that they try to match as few as possible (non-greedy), while * and + always try to match as many as possible (greedy).
Upvotes: 5