本文介绍了正则表达式匹配星号和换行符之间的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

blah blah * Match this text Match this text
            Match this text
            Match this text
            Match this text
            *
more text more text

如何使用换行符从星号内部获取字符串?

How to get string from inside the asterisk with the line breaks?

推荐答案

您可以在此处使用否定匹配。请注意,我转义 \ 此示例的文字换行符。

You can use a negated match here. Notice that I escaped \ the literal newline for this example.

var myString = "blah blah * Match this text Match this text\
            Match this text\
            Match this text\
            Match this text\
            *\
more text more text";

var result = myString.match(/\*([^*]*)\*/);
console.log(result[1]);

// => " Match this text Match this text            Match this text            Match this text            Match this text            "

参见

如果你不想要前导空格或尾随空格,你可以使用以下内容使它变得非贪婪。

If you don't want the leading or trailing whitespace, you can use the following to make it non greedy.

var result = myString.match(/\*\s*([^*]*?)\s*\*/);
console.log(result[1]);

// => "Match this text Match this text            Match this text            Match this text            Match this text"

这篇关于正则表达式匹配星号和换行符之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 22:52