Javascript 使用正则表达式从文本中获取字符串
如何仅获取Javascript 使用正则表达式从文本中获取字符串,javascript,regex,Javascript,Regex,如何仅获取材料[amhere]中的文本 例如,来自 PROD_RULE0001:WARNING: Metric[amhere] exceeded the UPPER WARNING limit[80.0] 。。。我只想要amhere 我试过: var strg = "WARNING: Material[amhere] exceeded the UPPER WARNING limit[80.0]"; var testRE = strg.match("Material\[(.*)\]"); ale
材料[amhere]
中的文本
例如,来自
PROD_RULE0001:WARNING: Metric[amhere] exceeded the UPPER WARNING limit[80.0]
。。。我只想要amhere
我试过:
var strg = "WARNING: Material[amhere] exceeded the UPPER WARNING limit[80.0]";
var testRE = strg.match("Material\[(.*)\]");
alert(testRE[1]);
那个?在*使它懒惰之后,所以。之后不会捕获所有内容
那个?在*使它懒惰之后,所以。不会在事后捕获所有内容。另一种方法可能是您想要使用的
var material="Material[";
var str="WARNING: Material[amhere] exceeded the UPPER WARNING limit[80.0]";
var n=str.indexOf(material);
var amhere=str.substring(n+material.length, str.length).split("]")[0];
也许你想用另一种方式
var material="Material[";
var str="WARNING: Material[amhere] exceeded the UPPER WARNING limit[80.0]";
var n=str.indexOf(material);
var amhere=str.substring(n+material.length, str.length).split("]")[0];
您的
*
表达式是贪婪的,因此会在结束]
时吃掉它,而不是与之匹配
除了@Telémako的解决方案外,另一种方法是通过说“匹配除]
以外的任何内容”来使表达式更严格。这也将解决问题
strg.match(/Material\[([^\]*)\]]/);
您的
*
表达式是贪婪的,因此会在结束]
时吃掉它,而不是与之匹配
除了@Telémako的解决方案外,另一种方法是通过说“匹配除]以外的任何内容”
来使表达式更严格。这也将解决问题
strg.match(/Material\[([^\]*)\]]/);