Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用正则表达式从文本中获取字符串_Javascript_Regex - Fatal编程技术网

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\[([^\]*)\]]/);