简体   繁体   English

使用正则表达式捕获文本行中的值

[英]Using regex to capture a value in a text line

I have a text line and I need capture the value "Keyword" key.我有一个文本行,我需要捕获值“关键字”键。

In this sample the value is "ConquestImageDate".在此示例中,值为“ConquestImageDate”。

With my code below I can capture the value as ConquestImageDate".使用下面的代码,我可以将值捕获为 ConquestImageDate"。

But it has a '"' on the end.但它的末尾有一个'"'。

I know I can use a replace to get rid off it.我知道我可以使用替换来摆脱它。

But, I´d like to do it in the regex.但是,我想在正则表达式中做到这一点。

let line =
  '(0008,0023) VERS="CQ"   VR="DA"   VM="1"    Keyword="ConquestImageDate"             Name="Conquest Image Date"';
const re = /Keyword=\"\s*(\S+)/;
m = re.exec(line);
console.log(m[1]);

You are not matching the closing " , and as exec might yield null you can check for m first before indexing into it.您不匹配关闭" ,并且由于 exec 可能会产生 null 您可以在索引之前先检查m

 let line = '(0008,0023) VERS="CQ" VR="DA" VM="1" Keyword="ConquestImageDate" Name="Conquest Image Date"'; const re = /Keyword="\s*(\S+)"/; m = re.exec(line); if (m) { console.log(m[1]); }

If there can also be unwanted whitespace chars at the end, you could making the \S non greedy.如果最后还可能有不需要的空白字符,则可以使\S非贪婪。

 let line = '(0008,0023) VERS="CQ" VR="DA" VM="1" Keyword="ConquestImageDate" Name="Conquest Image Date"'; const re = /Keyword="\s*(\S*?)\s*"/; m = re.exec(line); if (m) { console.log(m[1]); }


You are matching Keyword which is singular, but if in any case you want to match spaces or newlines as well between the double quotes您正在匹配单数的Keyword ,但如果在任何情况下您想在双引号之间匹配空格或换行符

\bKeyword="\s*([^"]*?)"

Regex demo正则表达式演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM