简体   繁体   English

如何在 JavaScript 中链式匹配和替换正则表达式

[英]How to chain match and replace regular expression in JavaScript

str="abc { return false;}"

I just want to get the word "false" from the string "str", as follows,我只想从字符串“str”中获取单词“false”,如下所示,

str.match(/return \w+;/g).replace(/return/,"")

It 's wrong !这是错的 ! How can I correct this expression to get the desired word?如何更正此表达式以获得所需的单词?

str.match will return an array with matching elements, not a single string. str.match将返回一个包含匹配元素的数组,而不是单个字符串。 This is why .replace fails.这就是.replace失败的原因。 A quick fix would be to add [0] to replace on the first array element like so: str.match(/return \\w+;/g)[0].replace(/return/,"")一个快速的解决方法是添加[0]来替换第一个数组元素,如下所示: str.match(/return \\w+;/g)[0].replace(/return/,"")

However, this will return false;但是,这将返回false; (not exactly what you want) and it will fail when there's no match at all: "Uncaught TypeError: Cannot read property '0' of null" (不完全是您想要的)并且当根本没有匹配项时它将失败:“未捕获的类型错误:无法读取 null 的属性 '0'”

A better way would be to use capture groups with paranthesis:更好的方法是使用带括号的捕获组:

var str= "abc { return false;}"
var re = /return (\w+);/g
var results = re.exec(str);

The result is again an array with the first element being the complete match, the second element is the first capture group: ["return false;", "false", index: 6, input: "abc { return false;}"]结果又是一个数组,第一个元素是完全匹配,第二个元素是第一个捕获组: ["return false;", "false", index: 6, input: "abc { return false;}"]

If the goal is just to extract the "returned value" from the string(function text definition) - it can be achieved through one operation without chaining:如果目标只是从字符串(函数文本定义)中提取“返回值” - 它可以通过一个操作来实现,无需链接:

var str = "abc { return true;}";
console.log(str.match(/return (\w+?);/)[1]); // outputs "true"

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

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