[英]Simple regex problem: Replacing words with '?'s
Alright, here's my current test function: 好了,这是我当前的测试功能:
function make_void( str )
{
var str_arr = str.split( /[\W]+/ );
var voidstr;
var newstr = "";
for ( var i = 0; i < str_arr.length; i++ )
{
voidstr = str_arr[i];
// if ( Math.random() <= 0.9 )
// {
voidstr = voidstr.replace( /\w/gi, "?" );
// }
newstr += voidstr + " ";
}
document.writeln( newstr );
}
The problem? 问题? Punctuations is lost. 标点符号丢失。
What's a good way to revise that such that they aren't? 有什么好方法可以修改它们而不是?
Split on whitespace ( \\s
) not on non-word ( \\W
) and you will retain punctuation. 在空白( \\s
)而不是非单词( \\W
)上分割,您将保留标点符号。
function make_void( str )
{
var str_arr = str.split( /\s+/ ); // !!!THIS LINE CHANGED!!!
var voidstr;
var newstr = "";
for ( var i = 0; i < str_arr.length; i++ )
{
voidstr = str_arr[i];
// if ( Math.random() <= 0.9 )
// {
voidstr = voidstr.replace( /\w/gi, "?" );
// }
newstr += voidstr + " ";
}
document.writeln( newstr );
}
update: example snippet using Array.join() method: 更新:使用Array.join()方法的示例代码段:
for ( var i = 0; i < str_arr.length; i++ )
{
// if ( Math.random() <= 0.9 )
// {
str_arr[i] = str_arr[i].replace( /\w/gi, "?" );
// }
}
var newstr = str_arr.join(' ');
Some sample text of what you're trying to match against might help. 您尝试匹配的一些示例文本可能会有所帮助。 (What do you actually want to keep ?) (您实际上想保留什么?)
For now, the following regex might help: 目前,以下正则表达式可能会有所帮助:
[\w\d,.?:;"'-()]
This matches words, digits, and a number of punctuation characters (though by no means all). 这匹配单词,数字和许多标点符号(尽管绝不是全部)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.