首页 > 解决方案 > 模式发现

问题描述

我有一个很长的字符串(称为'my_string'),没有包含新行。我一直在尝试在 JavaScript 中使用正则表达式来查找“my_string”中的特定单词。下面是代码说明

my_string=`Type of reaction engine discharging a fast-moving jet that generates thrust by jet propulsion. While this broad definition can include rocket, water jet, and hybrid propulsion, the term jet engine typically refers to an internal combustion airbreathing jet engine such as a turbojet, turbofan, ramjet, or pulse jet.[1] In general, jet CP_COLOR_B[#240025: engines]CP_COLOR_E are internal combustion engines. jet engines typically feature a rotating air CP_COLOR_B[#254117: compressor]CP_COLOR_E powered by a turbine, with the leftover power providing thrust through the propelling nozzle—this CP_COLOR_B[#2424df: combined]CP_COLOR_E is known as the Brayton thermodynamic cycle.`; 

var free_10_array = my_string.split("\n");
var free_10 = '';
for(var _10 in free_10_array){
   free_10+=free_10_array[_10];
}

const my_patt = new RegExp("(CP_COLOR_B\\[.+\\]CP_COLOR_E)", "gi");
var result_array = my_string.match(my_patt);
console.log(result_array);

我期望数组result_array 的长度为三(3),因为只有三(3)个模式(CP_COLOR_B[#240025:引擎]CP_COLOR_E,CP_COLOR_B[#254117:压缩器]CP_COLOR_E和CP_COLOR_B[#2424df:组合]CP_COLOR_E ) 我的目标是找到。相反,我得到了一个元素数组,其他字符串仅附加到第一个匹配的模式。我很乐意以这种形式获得结果,例如:

output=['CP_COLOR_B[#240025: engines]CP_COLOR_E','CP_COLOR_B[#254117: compressor]CP_COLOR_E','CP_COLOR_B[#2424df: combined]CP_COLOR_E']

标签: javascriptregex

解决方案


除了你的正则表达式中的一些小错误之外,你需要使用.+?而不是.+,因为第二个是“贪婪的”,这意味着它会尽可能多地匹配。

my_string=`Type of reaction engine discharging a fast-moving jet that generates thrust by jet propulsion. While this broad definition can include rocket, water jet, and hybrid propulsion, the term jet engine typically refers to an internal combustion airbreathing jet engine such as a turbojet, turbofan, ramjet, or pulse jet.[1] In general, jet CP_COLOR_B[#240025: engines]CP_COLOR_E are internal combustion engines. jet engines typically feature a rotating air CP_COLOR_B[#254117: compressor]CP_COLOR_E powered by a turbine, with the leftover power providing thrust through the propelling nozzle—this CP_COLOR_B[#2424df: combined]CP_COLOR_E is known as the Brayton thermodynamic cycle.`;

// Note the ".+?"
const my_patt = /CP_COLOR_B\[.+?\]CP_COLOR_E/g;

const result_array = my_string.match(my_patt);

console.log(result_array);
console.log(result_array.length);

这是关于贪婪与懒惰的更好解释:在正则表达式的上下文中,“懒惰”和“贪婪”是什么意思?


推荐阅读