简体   繁体   中英

javascript regular expression ignore condition between the text

I have a text for example as below:

"head1>data1,data2,data3|head2>data1,data2,data3|head3>data3,data4,data5**

now I want to replace ">data1..|" with "|"

I am using this: ".replace(/>\\S+\\||>\\S+$/g,"|");"

But this is not helping as it gives me data as below:

"head1|head3|" instead of "head1|head2|head3|"

I am unable to find the right method.

You can use

>\S+?(?:\||$)

See the regex demo

The point is to make \\S+ lazy, and to shorten the pattern we can use place the >\\S+? before the alternation group.

Pattern details :

  • >\\S+? - a literal > followed with 1+ non-whitespace symbols but as few as possible up to
  • (?:\\||$) - a literal | or the end of string.

A simple approach :), was trying like this

 var str = "head1>data1,data2,data3|head2>data1,data2,data3|head3>data3,data4,data5"; console.log(str.replace(/>[a-z1-9,]+/g,"|").replace(/\\|+/g, "|")); 

>[a-z1-9,]+ will select >data1,data2,data3

and then replaced multiple | with single |

:)

You can use:

>[a-z0-9,]+\\|

and then replace this with single | every time.

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