[英]Regex select all after nth occurance of character
我有一個以下格式的字符串,我試圖在第 3 次出現“:”字符后返回所有數據,如下例所示。
user_name_1, 10:46:36 activity_name_1 : the text to be returned
到目前為止,我有正則表達式\:.*
在第一次出現后返回所有內容,例如。 :46:36 activity_name_1: the text to be returned
如果我將其修改為\:{3}.*
例如。 要查找第三個實例,正則表達式不會返回任何匹配項。 看起來它應該是一個非常簡單的查詢,但我嘗試過的任何東西似乎都不起作用。
我已經發現以下問題find value after nth occurence of - using RegEx但是在這種情況下,它們只返回第 n 個字符后的下 3 位數字,而不是整個剩余字符串。
我建議不要為此使用正則表達式。 split()
通過:
字符拆分字符串並刪除結果數組的前兩個元素。
如有必要,您可以使用join()
將結果轉回字符串:
let input = 'user_name_1, 10:46:36 activity_name_1: the text to be returned: foo: bar'; let arr = input.split(':'); arr.splice(0, 3); console.log(arr); let output = arr.join(':').trim(); console.log(output);
您可以使用
^(?:[^:]*:){3}\s*(\S.*)
請參閱正則表達式演示。 詳情:
^
- 字符串的開始(?:[^:]*:){3}
- 除了:
然后是:
字符以外的任何零個或多個字符出現三次\s*
- 零個或多個空格(\S.*)
- 第 1 組:一個非空白字符,然后是該行的 rest。請參閱 JavaScript 演示:
const text = "user_name_1, 10:46:36 activity_name_1: the text to be returned"; const match = text.match(/^(?:[^:]*:){3}\s*(\S.*)/) if (match) { console.log(match[1]) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.