JSの正規表現で困っています
変数 "text" から 変数 "searchText" を正規表現を用いて検出させたいんですが,どうにも上手くいきません.
js
1let text = `# This is the code written in python.@n@value1 = 5@n@value2 = 4@n@@n@def add(a, b):@n@ """ add up@n@ ----@n@ Args:@n@ a: number@n@ b: number@n@ ----@n@ Return:@n@ a + b@n@ """@n@ return a + b@n@@n@total = add(value1, value2) # Calculation result@n@print(f"{value1} + {value2} = {total}")`; 2let searchText = `""" add up@n@ ----@n@ Args:@n@ a: number@n@ b: number@n@ ----@n@ Return:@n@ a + b@n@ """`; 3 4let regexp = new RegExp(searchText , 'g'); 5 6console.log(text.search(regexp));
出力結果
-1
おおよそどこかがおかしいのでしょうが,全くわからなくて困っています.
知恵をお貸しくださいm(_ _)m.
色々試したことを以下に書いておきます.
- ”text” の中に,検索文字 (searchText) があるのか.
出力結果js
1let substrText = text.substr(88, 102); 2 3console.log(substrText); 4if (substrText === searchText) { 5 console.log("found"); 6}
""" add up@n@ ----@n@ Args:@n@ a: number@n@ b: number@n@ ----@n@ Return:@n@ a + b@n@ """
found - 他の検索文字は検出できるのか.
出力結果js
1let searchText2 = `# This is the code written in python.@n@`; 2let searchText3 = `# Calculation result@n@`; 3 4let regexp2 = new RegExp(searchText2 , 'g'); 5console.log(text.search(regexp2)); 6 7let regexp3 = new RegExp(searchText3 , 'g'); 8console.log(text.search(regexp3));
0
241

回答2件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
また依頼した内容が修正された場合は、修正依頼を取り消すようにしましょう。
2022/11/30 04:53
2022/11/30 05:01