私はこの正規表現を使用しています
/(?:[^ .,;:]+[ .,;:]+){3}(?:term1|term2)(?:[ .,;:]+[^ .,;:]+){3}/gi
選択した用語と前後の3つの単語を抽出します。選択した用語を含む行を抽出するように正規表現を変更したいと思います。線は\nで囲まれますが、先頭と末尾のスペースもトリミングしたいと思います。
それを行うために正規表現を変更するにはどうすればよいですか?
入力例:
This line, containing term2, I'd like to extract.
This line contains term13 and I'd like to ignore it
This line, on the other hand, contains term1, so let's keep it.
出力は
This line, containing term2, I'd like to extract.
This line, on the other hand, contains term1, so let's keep it.
以下の変更するコードを参照してください。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<script>
var Input = " This line, containing term2, I'd like to extract."
Input += " This line contains term13 and I'd like to ignore it."
Input += " This line, on the other hand, contains term1, so let's keep it."
var matches = Input.match(/(?:[^ .,;:]+[ .,;:]+){3}(?:term1|term2)(?:[ .,;:]+[^ .,;:]+){3}/gi);
var myMatches = ""
for (i=0;i<matches.length;i++)
{
myMatches += ("..." + matches[i] + "...\n"); //assign to variable
}
alert(myMatches)
</script>
</body>
</html>