简体   繁体   English

Javascript Regex取代第6次出现; (分号)with; \\ n(分号和换行符)

[英]Javascript Regex replace the 6th occurrence of ; (semicolon) with ;\n (semicolon and newline)

string = "bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;bla;";

bla is wildcard. bla是通配符。

I want to update my string by inserting a newline (\\n) at every 6th occurrence of a semicolon (;) 我想通过在分号(;)的每第6次出现时插入换行符(\\ n)来更新我的字符串

I have been trying to do this with regex: 我一直试图用正则表达式做到这一点:


var myregexvar = textbox.value;

myregexvar = myregexvar.replace(/\u003b.*\u003b.*\u003b.*\u003b\b/, /$1\n/);

/u003b is the unicode character code for ';' / u003b是';'的unicode字符代码

it doesnt work. 它不起作用。 help! 救命!

Try matching (([^;]*;){5}[^;]*); 尝试匹配(([^;]*;){5}[^;]*); and replacing with $1\\n . 并替换为$1\\n

The first grouped expression ([^;]*;){5} looks for five bla; 第一个分组表达式([^;]*;){5}寻找五个bla; . Then [^;]* takes the sixth bla (without the ;). 然后[^;]*取第六个bla (没有;)。 All of that gets grouped into $1 . 所有这些都归为$1 Then the last semicolon is matched separately, so that it is left out and replaced with the \\n from the replacing expression. 然后单独匹配最后一个分号,以便将其省略并替换为替换表达式中的\\n

Edit 编辑

Didn't realize you wanted to add \\n after every sixth semicolon, not replace. 没有意识到你想在每六个分号后添加 \\n ,而不是替换。 You can use this simpler match expression: ([^;]*;){6} . 您可以使用这个更简单的匹配表达式: ([^;]*;){6}

hopefully this algorithm may help u 希望这个算法可以帮助你

$occurance = 6;
$count = 0;
while (/\u003b/gi) {
    if (++$count == $occurance) {
        myregexvar.replace(/\u003b/, /\n/);        
    }
}

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

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