简体   繁体   中英

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"
  2. "y" will always be the value between the last occurrence of "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"

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

  • Use (?<=" + 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.

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