Recommended online re site: regex101.com/

The basic grammar

  • +? : Repeat the last character as little as possible

Instead of going back and rushing to the end

Similar to “+”, “? The repetition of * “is also greedy. Match as many as you can

  • ? : tells the engine to match leading characters 0 times or once. In fact the leading character is optional.
  • + : tells the engine to match leading characters one or more times
  • * : tells the engine to match leading characters 0 or more times

Memory:? “+” *

Example 1.

Regular: <. +? > This is a first test

Lazy repetition, so the engine extends lazy repetition instead of reducing it, so “<.+” is now expanded to “<EM”.

Better: < [^ >] + >

Example 2.

Regular: \ / ~). +? (~ \ /)

  • Target

Additional hospitalization guarantee /~3//~/^=~/~/~~~~~~22~/11 111/~ee~/

  • result

/~3//~/ /~/~~~~~~22~/ /~ee~/

  • application
const regText = txt => { if (! txt) return ''; / / the match Text "hospital additional protection / ~ 3 / / / ^ = ~ / ~ ~ ~ ~ ~ ~ ~ 22 ~ / 11111 / ~ ee ~ /" / / to 'hospital additional protection < sub > 3 / / < / sub > ^ = ~ < sub > / 22 ~ ~ ~ ~ ~ ~ < / sub > 11111 < sub > ee < / sub >' const regtxt = TXT. Match (/ (\ / ~). +? (~\/)/gm) || []; regtxt.map(item => { let newItem = item.replace(/^\/~/, '<sup>'); newItem = newItem.replace(/~\/$/, '</sup>'); txt = txt.replace(item, newItem); return item; }); return txt; };Copy the code

Regular-oriented engine. Js text-oriented engines are not backtracking. Lazy repetition is not supported.