简体   繁体   中英

How to get string between two strings when there are escaping characters

I am trying to get string between two strings and it works like this:

if (text.toLowerCase().indexOf("[CUSTOMTAG]") >= 0) {
      _data = /\[CUSTOMTAG](.*?)\[\/CUSTOMTAG]/g.exec(text);
      if (_data[1] && _data[1].length > 0) {
        const data = _data[1];
      }
    }

But I have problem when string between contains something like:

[CUSTOMTAG]this is some
[/ru ugly content here[/CUSTOMTAG]

I am getting exception here Cannot read property '1' of null because parsing fail. How I can ignore excaping characters between?

It's not elegant but works. You may need to make some adjustments but it's an alternative:

 var input = `[CUSTOMTAG]this is some [/ru ugly content here[/CUSTOMTAG] [CUSTOMTAG]test2[/CUSTOMTAG]`; var startIndex = 0, endIndex = 0, results = []; while ((endIndex = input.indexOf("[/CUSTOMTAG]", endIndex)) >= 0 && (startIndex = input.indexOf("[CUSTOMTAG]", startIndex)) >= 0) { results.push(input.substring(startIndex + "[CUSTOMTAG]".length, endIndex)); endIndex += "[/CUSTOMTAG]".length; startIndex += "[CUSTOMTAG]".length; } console.log(results); 

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