正则表达式匹配星号和换行符之间的字符串
例:
blah blah * Match this text Match this text Match this text Match this text Match this text * more text more text
如何使用换行符从星号内部获取字符串?
你可以在这里使用否定的匹配。 请注意,我转义了此示例的文字换行符。
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"
[\s\S]
匹配任何空格和任何非空格字符。 即任何角色,甚至是换行符。 (在这里测试)。
\*[\s\S]*\*
另外,检查这个问题 。
试试这个:/( /(\*)([^\0].+)*(\*)/g
:
现场演示
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!"); }
这些答案对您现在和将来都有所帮助。
从控制台:
> "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 "