简体   繁体   English

JavaScript Regex返回x之间最后一次出现y,而忽略double x的第二次出现

[英]JavaScript Regex return the last occurrence of y between x while ignoring double x's second occurrence

Okay so the title must be a head scratcher, but here is the full string: 好的,标题一定是头上的划痕,但这是完整的字符串:

y = "_target"
x = "_"

string A = "prefix_param_name_id_set_selected_param_name_index__target_"
string B = "prefix_param_name_id_set_selected_param_name_index_target_"
  1. regex looks for "y" 正则表达式查找“​​ y”
  2. "y" will always be the value between the last occurrence of "x" “ y”将始终是最后一次出现的“ x”之间的值
  3. if the last occurrence of "x" is preceded with double "x" then regex assumes the second part of double "x" is part of "y" 如果最后出现的“ x”前面带有双精度“ x”,则正则表达式假定双精度“ x”的第二部分是“ y”的一部分

so returning "y" where at one instance "y" may be "_target" and at another "y" may be "target" 因此返回“ y”,其中在某些情况下“ y”可能是“ _target”而在另一个“ y”可能是“ target”

This is where I am at: 是我在这里:

var str = "prefix_param_name_id_set_selected_param_name_index__target_";
alert(str.match(/\(([^)]*)\)[^(]*$/)[1]);

returns "target"; 返回“目标”; it should be "_target". 它应该是“ _target”。

UPDATE: 更新:

Please note that "y" is a variable and is unknown. 请注意,“ y”是一个变量,未知。 str is known, but the regex does not know what "y" is, only that it is found between at the last occurrence of "x" str是已知的,但正则表达式不知道“ y”是什么,只是在最后一次出现“ x”之间找到它

You need to use x and y to create the regular expression 您需要使用xy创建正则表达式

var y = "_target";
var x = "_";
var regexp = new RegExp("(?<=" + x + ")(" + y + ")(?=" + x + ")", "g");
var input = "prefix_param_name_id_set_selected_param_name_index__target_";
var matches = input.match(regexp);

matches outputs matches输出

["_target"] [“_目标”]

Explanation 说明

  • Use (?<=" + x + ") to check if y follows x 使用(?<=" + x + ")检查y是否跟随x
  • (" + y + ") captures y (" + y + ")捕获y
  • (?=_) checks if x follows y as well. (?=_)检查x跟随y

Demo 演示版

 var y = "_target"; var x = "_"; var regexp = new RegExp("(?<=" + x + ")(" + y + ")(?=" + x + ")", "g"); var input = "prefix_param_name_id_set_selected_param_name_index__target_"; var matches = input.match(regexp); console.log(matches); 

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

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