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"
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".
UPDATE:
Please note that "y" is a variable and is unknown. str is known, but the regex does not know what "y" is, only that it is found between at the last occurrence of "x"
You need to use x
and y
to create the regular expression
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
["_target"]
Explanation
(?<=" + x + ")
to check if y follows x
(" + y + ")
captures y
(?=_)
checks if x
follows y
as well. 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.