[英]Javascript Regular Expression to search a multiline textarea for an expression
假設有一個textarea具有以下值('*'用作項目符號點):
*south
*north
*west
我希望能夠使用正則表達式自動生成這些單詞的數組,就像這樣。
["south","north","west"]
以下是我試過的表達方式。
/\*.*/gm.exec(text)
不幸的是,它返回了這個。
["*south"]
顯然,RegExp識別出有一個換行符,它只返回第一個項目,但它沒有拾取第2行和第3行。
/\*.*/gm.exec('*south \n *north')
這也有相同的結果。
你將不得不運行一個循環。
var re = /\*(.*)/gm;
var str = '*south\n*north\n*west ';
var m;
while ((m = re.exec(str)) !== null) {
// View your result using the m-variable.
// eg m[0] etc.
}
見演示。
https://regex101.com/r/iJ7bT6/11
或者你分開(?=\\*)
參見演示。
你需要告訴正則表達式引擎在^
行的開頭匹配,然后用一對非轉義括號捕獲第一個*
之后的部分。 然后,您可以在循環中使用RegExp#exec()
,並獲得組1中所需的值。 ^\\s*\\*\\s*(.*)
正則表達式匹配:
^
- 一行的開始(由於/m
多行修飾符) \\s*
- 零個或多個空白符號 \\*
- 文字星號 \\s*
- 再次,可選的空格 (.*)
- 除換行符之外的零個或多個字符。 var re = /^\\s*\\*\\s*(.*)/gm; var str = '*south\\n *north\\n* west '; var res = []; while ((m = re.exec(str)) !== null) { res.push(m[1]); } document.write("<pre>" + JSON.stringify(res, 0, 4) + "</pre>");
另一種方案:
用換行符拆分(如果可以有\\r
或\\n
可以在這里使用正則表達式)然后去除初始*
:
var str = '*south\\n*north\\n*west '; var res = []; str.split(/[\\r\\n]+/).forEach(function(e) { res.push(e.replace(/^\\s*\\*\\s*/, '')); }); document.write("<pre>" + JSON.stringify(res, 0, 4) + "</pre>");
@VKS解決方案有效,但如果不是必須使用正則表達式,那么試試這個小提琴
<textarea id="textA1"></textarea>
$( "#textA1" ).blur( function(){
var value = $( this ).val();
console.log( value.split( "\n" ) );
} )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.