简体   繁体   中英

find a single occurrence of a string, then multiple matches of another pattern

Is it possible to match a certain string once, and then multiple occurances of a string pattern multiple times, replacing each with itself, appended with another value (eg, line break)?

<!--HTML-->
<textarea id="i"></textarea>

JS

var s = "some-string-to-begin%a-b,c-d,e-f";

var re = /^(.*?)%(((\w+)\-(\w+)),?)*/g;

console.log(s.match(re)); //matches the whole string

var res = s.replace(re, "$1\n$2\n$3\n$4\n$5");

$("#i").val(res)

html:

<textarea>
some-string-to-begin
e-f
e-f
e
f
</textarea>

successfully matches the string, but I cannot seem to get a repetitive replacement of the word pairs.

JSBIN

You'll have to use a function replacement to do what you want:

s.replace( /^(.*?)%(.*)/, function(s,a,b) { 
    return a + '\n' + b.replace( /(\w+)-(\w+),?/g, '$1\n$2\n' ); 
});

My general philosophy is "why pull your hair out trying to make one uber-regex when you can easily accomplish your goal with two?" In this case, we match the greater string ("ab,cd,ef"), then match the individual pairs and do the replacement.

Without knowing the greater context of your problem, it's hard to say, but it seems like you could accomplish your goal in a less complicated fashion by splitting and re-joining:

var parts = s.split( '%' );
var result = [ parts[0] ].concat( parts[1].split( /[,-]/ ) ).join( '\n' );

If your string will always be comma/percent delineated, you could do something like this:

var s = "some-string-to-begin%a-b,c-d,e-f",
  replacement = s.split(/[%,]/g).join('\n'); // split by % or , and then join by linebreak
$("#i").val(replacement);

JSBIN

(Not sure if you're also trying to separate the 'a-b' into 'a\\nb' as well.)

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