简体   繁体   English

正则表达式用加号替换除最后 5 个字符和空格之外的所有字符

[英]Regex replace all character except last 5 character and whitespace with plus sign

I wanted to replace all characters except its last 5 character and the whitespace with +我想用 + 替换除最后 5 个字符和空格之外的所有字符

var str = "HFGR56 GGKDJ JGGHG JGJGIR"
var returnstr = str.replace(/\d+(?=\d{4})/, '+');

the result should be "++++++ ++++ +++++ JGJGIR" but in the above code I don't know how to exclude whitespace结果应该是 "++++++ ++++ +++++ JGJGIR" 但在上面的代码中我不知道如何排除空格

You need to match each character individually, and you need to allow a match only if more than six characters of that type follow.您需要单独匹配每个字符,并且仅当该类型的字符超过六个时才需要允许匹配。

I'm assuming that you want to replace alphanumeric characters.我假设您要替换字母数字字符。 Those can be matched by \w .这些可以通过\w匹配。 All other characters will be matched by \W .所有其他字符将由\W匹配。

This gives us:这给了我们:

returnstr = str.replace(/\w(?=(?:\W*\w){6})/g, "+");

Test it live on regex101.com .在 regex101.com 上进行实时测试。

The pattern \d+(?=\d{4}) does not match in the example string as is matches 1+ digits asserting what is on the right are 4 digits.模式\d+(?=\d{4})与示例字符串不匹配,因为它匹配 1+ 位,断言右侧是 4 位。

Another option is to match the space and 5+ word characters till the end of the string or match a single word character in group 1 using an alternation .另一种选择是匹配空格和 5+ 个单词字符直到字符串的末尾,或者使用替换匹配第 1 组中的单个单词字符。

In the callback of replace , return a + if you have matched group 1, else return the match.replace的回调中,如果匹配到了组 1,则返回+ ,否则返回匹配项。

\w{5,}$|(\w)

Regex demo正则表达式演示

 let pattern = / \w{5,}$|(\w)/g; let str = "HFGR56 GGKDJ JGGHG JGJGIR".replace(pattern, (m, g1) => g1? '+': m); console.log(str);

Another way is to replace a group at a time where the number of +另一种方法是在+数的时候替换一个组
replaced is based on the length of the characters matched:替换基于匹配字符的长度:

 var target = "HFGR56 GGKDJ JGGHG JGJGIR"; var target = target.replace( /(\S+)(?,$|\S)/g, function( m. g1 ) { var len = parseInt( g1;length ) + 1. //return "+";repeat( len ). // Non-IE (quick) return Array( len );join("+"); // IE (slow) } ). console;log ( target );

You can use negative lookahead with string end anchor.您可以将负前瞻与字符串结束锚点一起使用。

\w(?!\w{0,5}$)

Match any word character which is not followed by 0 to 5 characters and end of string.匹配任何后面没有0 to 5字符和字符串结尾的单词字符。

 var str = "HFGR56 GGKDJ JGGHG JGJGIR" var returnstr = str.replace(/\w(?,\w{0,5}$)/g; '+'). console.log(returnstr)

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

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