Advanced Regular Expression

String:

Ventilator Set:\n FiO2 ≤ 40%\nDrug use:\n NO\nWeaning trials:\n NO\nStop reason:\n neurologic factors\n備註:\n

Purpose

Find the second \n and replace it with another character

Solution

var pattern = /\\n(.*?(?:\\n|$))/gm;
var sub = '$1<br/>';
read = read.replace(pattern, sub);

https://regex101.com/r/t9gozM/1

Pattern Explanation: 在\n後面找一個最近的\n或是結尾之間的字串

Notes:

  • (?:)
    括號裡面的內容不產生指標($1之類的)
  • ^
    一行的開始
  • $
    一行的結束
  • (?=p)
    正前向聲明,要求接下來的字元都與樣式p相符,但是不包括比對中的那些字元
  • (?!p)
    反前向聲明,要求接下來的字元不與樣式p相符

    Route::get('/{category}/{cat_lv3}', '[email protected]')
                    ->where('cat_lv3', '^(?!\d+\-).+');
    
    /*
    /products/pumps/floor-pumps
    match
    
    /products/floor-pumps/1322-JOEBLOW®-BOOSTER
    Not match
    */
  • 重複字元(如*)後加上? – 非貪婪的重複比對
    /a+/
    /a+?/ -> 只符合一個以上的字母a

Reference:

  1. Completed Usages
    https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Regular_Expressions
  2. Online Test
    https://regex101.com/r/FU2s1H/1