简体   繁体   English

使用标签之间的文本更改标签

[英]Changing the tags with the text between the tags

My title sounds complicated so i'll try to simplify it by making an example 我的标题听起来很复杂,所以我将通过举例来简化它

i have these selfmade tags like 我有这些自制标签,例如

{tag}tagtext{tag}

and i'm trying to change this into 我正在尝试将其更改为

<span>same tagtext</span>

i tried using regex but i couldn't really figure out how could i get the text between the tags and then also change the tags to something else. 我尝试使用正则表达式,但我无法真正弄清楚如何获取标签之间的文本,然后将标签更改为其他内容。

i got the text between the tags with 我得到了标签之间的文字

string.match('{tag}(.*){tag}');

Also all the tags are same and for some reason the match function gave me only the first result it found. 同样,所有标签都是相同的,由于某种原因,match函数只给了我找到的第一个结果。 I guess it has something to do with my regex. 我想这与我的正则表达式有关。

Also i do not want to do it with a loop because it will start to work as an live editor and i need to keep the performace fast. 我也不想做一个循环,因为它将开始作为实时编辑器工作,我需要保持性能快速。

/(\{tag\})(.*?)\1/g
 ^^^^^^^^^  ^^ ^^ ^  
    1        2  3 4
1: Match tag and put in group 1
2: *? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
3: matches the same text as most recently matched by the 1st capturing group
4: Global pattern flags, all matches.

 var temp = "{tag}tagtext1{tag}{tag}tagtext2{tag}\\n{tag}tagtext3{tag}{tag}tagtext4{tag}"; console.log(temp.replace(/(\\{tag\\})(.*?)\\1/g,"<span>$2</span>")); 

Is this your expect result ? 这是您期望的结果吗?

<span>tagtext1</span><span>tagtext2</span>
<span>tagtext3</span><span>tagtext4</span>

You have to use the global modifier or g after a RegEx expression in order to enable all matches. 您必须在RegEx表达式后使用global修饰符或g才能启用所有匹配项。 What language are you using for RegEx? 您正在使用哪种语言进行RegEx?

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

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