Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 正则表达式提取包含术语的行_Javascript_Regex - Fatal编程技术网

Javascript 正则表达式提取包含术语的行

Javascript 正则表达式提取包含术语的行,javascript,regex,Javascript,Regex,我一直在用这个正则表达式 /(?:[^ .,;:]+[ .,;:]+){3}(?:term1|term2)(?:[ .,;:]+[^ .,;:]+){3}/gi 提取所选术语以及前后3个单词。我想更改正则表达式,以便提取包含所选术语的行。该行将以\n为边界,但我还希望修剪前导空格和尾随空格。 如何修改正则表达式来实现这一点 输入示例: This line, containing term2, I'd like to extract. This line contai

我一直在用这个正则表达式

/(?:[^ .,;:]+[ .,;:]+){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>

无标题文件
var Input=“此行包含term2,我想提取。”
Input+=“此行包含term13,我想忽略它。”
另一方面,这一行包含term1,所以我们保留它
var matches=Input.match(/(?:[^,;:]+[,;:]+){3}(?:term1 | term2)(?:[,;:]+[^,;:]+){3}/gi);
var myMatches=“”

对于(i=0;i,如Asad所指出的,您可以使用\b作为单词边界,这样term1就不会与term13匹配

正则表达式:

^ *(.*\b(?:term1|term2)\b.*) *$
你应该做你想做的。你的比赛将在第一个(也是唯一的)捕获组中。只需循环它们,你就完成了


一个建议:如果你的单词不太可能包含特殊字符,你可以使用单词边界。所以…你需要的是额外的行,其中包含
“term1”
“term2”
?如此接近,我可以尝到。啊,但我看到你的行没有我犯过的错误。