如何从正则表达式中的字符串中获取特定文本
How to get specific text from a string in regex
我有一个字符串,我需要从中提取特定的文本
let str = 'id = "Test This is" id ="second" abc 123 id ="third-123"';
let res = str.match(/[^id ="\[](.*)[^\]]/g);
console.log(res);
我只想要 id 中的文本 ['Test This is','second','third-123']
但是我得到 [ 'Test This is" id ="second" abc 123 id ="third-123"' ]
第一个 id 之后的整个文本,我不需要 want.I 需要有关模式的帮助。
您的模式使用否定字符 class,您在其中排除匹配列出的单个字符,并且还排除匹配 [
和 ]
,它们不存在于示例数据中。
这样你就可以将字符串中的第一个字符 T 与 [^id ="\[]
匹配,并匹配字符串中的最后一个字符 ; [^\]]
和 .*
之间的所有字符串。
我建议使用否定字符 class 来排除与 "
的匹配:;
\bid\s*=\s*"([^"]*)"
let str = 'id = "Test This is" id ="second" abc 123 id ="third-123"';
let res = str.matchAll(/\bid\s*=\s*"([^"]*)"/g);
console.log(Array.from(str.matchAll(/\bid\s*=\s*"([^"]*)"/g), m => m[1]));
您可以将其简化为一个非贪婪的正则表达式,而不管引号在字符串中的位置:
let str = 'id = "Test This is" id ="second" abc 123 id ="third-123"';
let res = str.match(/".*?"/g);
console.log(res);
我有一个字符串,我需要从中提取特定的文本
let str = 'id = "Test This is" id ="second" abc 123 id ="third-123"';
let res = str.match(/[^id ="\[](.*)[^\]]/g);
console.log(res);
我只想要 id 中的文本 ['Test This is','second','third-123']
但是我得到 [ 'Test This is" id ="second" abc 123 id ="third-123"' ]
第一个 id 之后的整个文本,我不需要 want.I 需要有关模式的帮助。
您的模式使用否定字符 class,您在其中排除匹配列出的单个字符,并且还排除匹配 [
和 ]
,它们不存在于示例数据中。
这样你就可以将字符串中的第一个字符 T 与 [^id ="\[]
匹配,并匹配字符串中的最后一个字符 ; [^\]]
和 .*
之间的所有字符串。
我建议使用否定字符 class 来排除与 "
的匹配:;
\bid\s*=\s*"([^"]*)"
let str = 'id = "Test This is" id ="second" abc 123 id ="third-123"';
let res = str.matchAll(/\bid\s*=\s*"([^"]*)"/g);
console.log(Array.from(str.matchAll(/\bid\s*=\s*"([^"]*)"/g), m => m[1]));
您可以将其简化为一个非贪婪的正则表达式,而不管引号在字符串中的位置:
let str = 'id = "Test This is" id ="second" abc 123 id ="third-123"';
let res = str.match(/".*?"/g);
console.log(res);