[英]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_"
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 您需要使用
x
和y
创建正则表达式
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 说明
(?<=" + 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.