使用正则表达式和JavaScript,每两个单词插入一个换行符。

3
我希望能制作一个正则表达式,每两个单词就插入一个回车...而且需要格式化的字符串是一个数组(这有什么区别吗?) 问题是:我两周前才听说过正则表达式,到目前为止,它让我感觉像有人在踩我的大脑。所以目前我想出了这个(请见谅...)
ticketName[i] = 'Lorem ipsum dolor sit amet consectetur adipisicing';
ticketName[i] = ticketName[i].replace(/(?:[a-zA-Z])* {2}/ig, ',');

令人惊讶的是,这并不起作用!

有人能帮帮我吗?

还有,当我完成这个任务之后,如果句子超过一定数量的字符,我需要将其末尾替换为“...”。如果你对此有任何见解,因为我可能也需要回来做这个任务... 在网站上搜索,只找到了将句子末尾替换为回车符号的方法。我想我的难题在于定义这个单词。 非常感谢。


1
你的正则表达式中哪里是回车符? - user2193789
逗号也用于分隔函数参数。因此,您实际上向替换函数提供了3个参数。要将逗号作为参数传递,您必须使用斜杠进行转义。 - user2193789
非常感谢大家!!!感谢你们对正则表达式工作原理的回答和详细解释。真是一支牛逼的社区!目前为止,没有一个正则表达式可以立即生效,但我想我可能做错了什么。我会在周末继续测试,并在周一回到论坛 :) - HowTo
好的,我测试了一下,正如我所想:其中许多都有效,但是我做错了...我忘记了我的变量是一个innerHTML,我只需要将\n更改为<br />...我知道对吧...再次感谢大家的答案以及教程链接。Floris我使用了正则表达式;)它非常好用! - HowTo
很不幸,我在这个网站上还太新了,无法被允许投票,所以我别无选择,只能将我的投票作为一种精神感应发送...嗯嗯 - HowTo
显示剩余4条评论
5个回答

2

你有很多选择。我只是想再加上一个选项,同时回答你的第二个问题:

var mytest = "lorem ipsum dolor sit amet consectetur adipisicing";
var newtext = mytest.replace(/(\w+\W+\w+)\W+/ig,"$1\n");
alert(newtext);

result:
lorem ipsum
dolor sit
amet consectetur
adipisicing

注意 - 最后一个单词('adipisicing')未匹配,因此未被替换。它只是在末尾(没有尾随\n)。
解释:
正则表达式:
(     start a capture group comprising:
\w+   one or more "word" characters
\W+   one or more "not a word" characters
\w+   one or more "word" characters
)     end capture group
\W    followed by non-word
/ig   case insensitive, global (repeat as often as possible)

并替换为:

$1    "The thing in the first capture group (everything matched in parentheses)
\n    followed by a newline

第二个问题:

顺便提一下,因为您问到了“其他”问题 - 如何在一定数量的单词后以 ... 结束句子,您可以这样做:

var abbrev = mytest.replace(/((\w+\W+){5}).*$/,"$1...");
alert(abbrev);

result:
lorem ipsum dolor sit amet ...

说明:
(    start capture group
(    start second group (to be used for counting)
\w+  one or more "word" characters
\W+  one or more "non word" characters
){5} match exactly five of these
)    end of capture group
.*$  followed by any number of characters up to the end of the string

并替换为

$1   the contents of the capture group (the first five words)
...  followed by three dots

一个问题有两个答案!

如果你想同时做这两件事,那么先缩短一个长句,然后将其分成更短的片段。使用正则表达式跨多行计算单词数量有点困难。


1
我希望你能找到这里发布的正则表达式解决方案之一适合你。
另外,也可以使用字符串的split()和substring()方法来实现相同的功能。下面的代码和fiddle这里展示了这种方法。不过这种方法没有使用正则表达式那么优雅。
示例源代码
ticketName = new Array();
ticketName[0] = 'Lorem ipsum dolor sit amet consectetur adipisicing';
tmparray = new Array();
tmparray = ticketName[0].split(" ");



finalName = ""; // hold final name
totallength=0;
maxlength = 30;

// add a carriage return (windows) every two words
for (var i=0; i<tmparray.length; i++){
    finalName += tmparray[i]+" ";
    if ((i>0) && (((i-1)%2) == 0))
        finalName +="\r\n";
}

// truncate result if exceed final length and add .... where truncated
if (finalName.length>maxlength)
    finalName= finalName.substring(0,maxlength)+ ".....";

alert(finalName);

嗯,在这种情况下,我宁愿使用正则表达式。不过还是谢谢你,因为我不知道在JS中也可以这样做。这可能会在其他用途上派上用场。 - HowTo

1
我认为这应该可以运行:

str.replace(/((\s*\w+\s+){2})/g, "$1\n");

例如:

var str = 'Lorem ipsum dolor sit amet consectetur adipisicing';
str.replace(/((\s*\w+\s+){2})/ig, "$1\n");
"Lorem ipsum 
dolor sit 
amet consectetur 
adipisicing"

正则表达式的解释:

(         -> start of capture group. We want to capture the two words that we match on
(         -> start of an inner capture group. This is just so that we can consider a "word" as one unit.
\s*\w+\s+ -> I'm consider a "word" as something that starts with zero or more spaces, contains one or more "word" characters and ends with one or more spaces.
)         -> end of capture group that defines a "word" unit.
{2}       -> we want two words
)         -> end of capture group for entire match.

在替换中,我们有$1\n,它简单地表示“使用第一个捕获组并附加一个换行符”。

Fiddle


0

尝试:

'Lorem ipsum dolor sit amet consectetur adipisicing'
  .match(/([a-z]+\s){2,2}/gi)
  .join('\n');

0

让我们从你的正则表达式中找出问题:
- [a-zA-Z] 你不需要指定 A-Z,因为你正在使用 i 修饰符
- {2} 如评论中Matt Ball所述,你只是想匹配两个连续的空格,你需要使用括号来重复整个组
- ',' 你说你想用回车 (\r) 替换逗号,但你插入了一个逗号

现在,我认为最好的匹配单词的方法如下:

/\b[a-z]+\b/

(这里为了\b,我们将使用惰性操作符)
你可以这样做:

replace(/(\b[a-z]+\b.*?\b[a-z]+\b)/, '$1\r')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接