簡體   English   中英

使用正則表達式在我選擇的前兩個相同字符之間查找文本

[英]Find text between the first two same characters of my choice with regex

假設以下輸出

20198818-119903 | firmware-check | passed: host test-1000 is connected to a test with Version: 333 | |
20198818-119903 | other-test-123 | passed: host test-1000 is connected to a test with 333:
20198818-119903 | test4| passed :| host | is connected to a test with 333
20198818-119903 | something | passed: host test-1000 is connected to a test with Version:

我想提取固件檢查,other-test-123,test4之類的東西

所以基本上前兩個豎線之間 所有內容

我試圖用txt2re解決此問題,但沒有按我的要求進行工作(例如,不忽略第三行的主機)。 我從未使用過正則表達式,也不想僅針對這種特殊情況學習它。 有人能幫助我嗎?

你可以用這個

^[^|]+\|([^|]+)

在此處輸入圖片說明

 let str = `20198818-119903 | firmware-check | passed: host test-1000 is connected to a test with Version: 333 | | 20198818-119903 | other-test-123 | passed: host test-1000 is connected to a test with 333: 20198818-119903 | test4| passed :| host | is connected to a test with 333 20198818-119903 | something | passed: host test-1000 is connected to a test with Version:` let op = str.match(/^[^|]+\\|([^|]+)/gm).map(m=> m.split('|')[1].trim()) console.log(op) 

該表達式將簡單地提取這些值:

.*?\|\s*(.*?)\s*\|.*

DEMO

 const regex = /.*?\\|\\s*(.*?)\\s*\\|.*/gm; const str = `20198818-119903 | firmware-check | passed : host test-1000 is connected to a test with Version: 333 | | 20198818-119903 | other-test-123 | passed : host test-1000 is connected to a test with 333: 20198818-119903 | test4| passed :| host | is connected to a test with 333 20198818-119903 | something | passed : host test-1000 is connected to a test with Version:`; const subst = `$1`; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log(result); 

您可以使用正則表達式/[^|]+\\|\\s*([^|]+)\\s*\\|.*/獲得|之間的第一個匹配項| 進入一個捕獲小組。 使用exec和while循環來獲取所有匹配項。

(您也可以使用matchAll跳過while循環,但它仍處於草稿狀態)

 let str = `20198818-119903 | firmware-check | passed : host test-1000 is connected to a test with Version: 333 | | 20198818-119903 | other-test-123 | passed : host test-1000 is connected to a test with 333: 20198818-119903 | test4| passed :| host | is connected to a test with 333 20198818-119903 | something | passed : host test-1000 is connected to a test with Version:`, regex = /[^|]+\\|\\s*([^|]+?)\\s*\\|.*/g, match, matches = []; while(match = regex.exec(str)) matches.push(match[1]) console.log(matches) // OR // matchAll is still in Draft status console.log( Array.from(str.matchAll(regex)).map(a => a[1]) ) 

正則表達式演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM