簡體   English   中英

如何使用單行從字符串中提取特定的 substring

[英]How to extract specific substring from a string using a one liner

輸入: parent/123/child/grand-child

預期 output: child

嘗試 1(?<=\/parent\/\d*)(.*)(?=\/.*)

錯誤: lookbehind 中的量詞使其寬度不固定,look behind 不接受 * 但我不知道數字的寬度,因此必須使用它

嘗試 2:(有效,但有 2 個襯墊):

const currentRoute='/parent/123/child/grand-child'
let extract = currentRoute.replace(/\/parent\/\d*/g, '');
extract = extract.substring(1, extract.lastIndexOf('/'));
console.log('Result', extract)  

如何使用單襯獲得提取物,最好使用正則表達式

怎么樣

currentRoute.match(/\/parent\/(?:.*)\/(.*)\//)[1]

您當前的模式將匹配123/child而不是child only 因為在\d*之后缺少正斜杠(注意*表示 0 次或更多次)

如果存在更多正斜杠,它也會由於.*而過度匹配(參見演示)。


相反,您可以使用捕獲組並使用match

parent\/\d+\/(\w+)\/

正則表達式演示

該值在捕獲組 1 中。

 let res = "parent/123/child/grand-child".match(/parent\/\d+\/(\w+)\//); if (res) console.log(res[1])


一個向后看以獲得價值child的模式可能是

(?<=parent\/\d*\/)([^\/]+)(?=\/)

正則表達式演示

請注意,這尚未得到廣泛支持。

 let res = "parent/123/child/grand-child".match(/(?<=parent\/\d*\/)([^\/]+)(?=\/)/); if (res) console.log(res[0])

如果格式固定,則使用.split("/")[2]獲取第三個元素

console.log(currentRoute.split("/")[2]);

“孩子”


要匹配字符串的部分,請使用.match(/^parent\/[^\/]+\/([^\/]+)/)[1]

console.log(currentRoute.match(/^parent\/[^\/]+\/([^\/]+)/)[1]);

“孩子”

暫無
暫無

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

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