我正在尝试找到特定的模式,然后按以下结尾行将文本分割。例如,我的文字看起来与此类似
{11/2/2018 8:09 AM} This item was created by. -John Doe
{11/2/2018 10:56 AM} This item was upated by -Sue Smith
{11/2/2018 10:58 AM} Does this item handle multiple lines?
Yes it does -Jane Sample
我当前正在使用以下javascript
var Notes = data.Notes.split(/-[\w ]+$/gmi);
$.each(Notes, function (index, note) {
console.log(note)
})
这样做确实很完美,但它会将文本分成几行
{11/2/2018 8:09 AM} This item was created by.
{11/2/2018 10:56 AM} This item was upated by
{11/2/2018 10:58 AM} Does this item handle multiple lines?
Yes it does
但是您可以看到它删除了用户名...
我该怎么写,以便以该特定模式分割字符串,但将用户名保留在字符串的末尾?
答案 0 :(得分:1)
一种方法是使用.match
代替.split
:
const text = `{11/2/2018 8:09 AM} This item was created by. -John Doe
{11/2/2018 10:56 AM} This item was upated by -Sue Smith
{11/2/2018 10:58 AM} Does this item handle multiple lines?
Yes it does -Jane Sample`;
const notes = text.match(/^[\s\S]*?-[\w ]+$/mg) || [];
for (const note of notes) {
console.log(note);
}
.split
可让您指定要丢弃的内容。 .match
可让您指定要保留的内容。在这里,我们要提取尽可能短的文本([\s\S]*?
,直到下次出现名称(-[\w ]+$
)为止的文本。