2017-12-15 5 views
1

私は、文字列正規表現で特殊文字列内の部分文字列を見つけるにはどうすればよいですか?

element : 1 

Description 
This is the description of item 1 
___________________ 

element : 2 

Description 
This is the description of item 2 
______________________ 

これがそのコードですがあります(包括的または排他的にそうでない

var string = "element : 1\n\nDescription\nThis is the description of item 1\n_________________\n\nelement : 2\n\nDescription\nThis is the description of item 2\n____________________________" 

と私は正規表現でelement : 1からelement : 2に始まる部分文字列を抽出することができるようにしたいが今の問題)

私は、次のコードを使用しますが、それはまだ動作しません:

var regexStr = /element : 1\s*\n(.*)element : 2/ 
var rx = new RegExp(regexStr, "i") 

console.log(string.match(rx)); //null 

答えて

3

あなたはa demo on regex101.comを参照して、複数行の改質剤と

^element(?:(?!^element)[\s\S])+ 

を使用することができます。これは言う内訳


:JavaScriptで

^element   # match element at the start of a line 
(?:    
    (?!^element) # neg. lookahead, making sure there's no element at the start of the line 
    [\s\S]  # ANY character, including newlines... 
)+    # ...as often as possible 
+0

これは正規表現エディタで完全に機能しますが、なぜここでは動作しないのですか? https://es6console.com/jb8g6b5d/ –

+1

@YouMa: 'multiline'フラグを追加する必要があります:' .../im' https://es6console.com/jb8h1ner/を参照してください。 – Jan

1

を、.ごと文字と一致していません。これは、行終了記号以外の任意の1文字に一致します。\n\r\u2028または\u2029です。代わりに

することはでき達[\s\S]:参考

/element : 1\s*\n([\s\S]*)element : 2/

\sは空白文字を意味し、\Sはその逆です。したがって、[\s\S]は、 "空白文字か空白文字でない任意の文字" ...したがって "任意の文字"です。

関連する問題