正则表达式匹配星号和换行符之间的字符串

时间:2013-12-24 00:11:04

标签: javascript jquery regex

示例:

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

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

4 个答案:

答案 0 :(得分:2)

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

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            "

请参阅Working demo

如果您不想要前导或尾随空格,可以使用以下内容使其不贪婪。

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"

答案 1 :(得分:0)

[\s\S]匹配任何空格和任何非空格字符。即任何角色,甚至是换行符。 (经过测试here)。

\*[\s\S]*\*

Also, check this SO question

答案 2 :(得分:0)

试试这个:/(\*)([^\0].+)*(\*)/g

Live Demo

var regex = /(\*)([^\0].+)*(\*)/g; 
var input = "* Match this text Match this text (this is a line break -> \n) Match this text (\n) Match this text Match this text * more text more text"; 
if(regex.test(input)) {
    var matches = input.match(regex);
    for(var match in matches) {
        alert(matches[match]);
    } 
}
else {
    alert("No matches found!");
}

答案 3 :(得分:0)

这些答案可以帮助nowfuture

从控制台:

> "blah blah * Match this text Match this text\
            Match this text\
            Match this text\
            Match this text\
            *\
more text more text".match(/[*]([^*]*)[*]/)[1]   

" Match this text Match this text            Match this text            Match this text            Match this text            "
相关问题