javascript - 模式发现
问题描述
我有一个很长的字符串(称为'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']
解决方案
除了你的正则表达式中的一些小错误之外,你需要使用.+?
而不是.+
,因为第二个是“贪婪的”,这意味着它会尽可能多地匹配。
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);
这是关于贪婪与懒惰的更好解释:在正则表达式的上下文中,“懒惰”和“贪婪”是什么意思?
推荐阅读
- chinese-locale - 如何识别中文文本中的声调?
- c++ - 如何在类参数中对字符串进行排序?
- python - 使用python显示和编辑绘图x和y轴
- r - 如何更改 facet_wrap 中面板的顺序和标签?
- swift - Swift Userdefaults 将 String 转换为 __NSCFString
- python - 如何加载多个训练和有效性数据来训练和验证 keras 模型
- android - 在 LinearLayout 中 layout_weight 如何与 wrap_content 和 Buttons 交互——为什么我会得到违反直觉的结果?
- javascript - window 对象中的 position.coords.latitude 在哪里?
- charts - 功率 bi 阈值图表
- python - 如何将整数str转换为嵌套列表中的整数