【问题标题】:JavaScript regex on textarea input文本区域输入上的 JavaScript 正则表达式
【发布时间】:2017-01-05 08:51:12
【问题描述】:

我正在尝试从文本区域字段中的 Apache 日志文件输入中提取所有 IP 地址。我正在使用正则表达式来提取 IP 地址。我想查看屏幕上打印的所有 IP 地址。 我无法理解我做错了什么。请帮忙

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<title>RegEx_example</title>
</head>
<body style = "background-color: lightgrey">
<center>
<h3><u>Log Miner</u></h3>
<br /><hr />
<h5>Paste your Apache log file in the box below and click on Mine!</h5>

<textarea  rows="25" cols="200" form="mine_log" id = "logs">

</textarea>

<form id = "mine_log" method = "" onsubmit="parseLogs(document.getElementById('logs').value)">
    <input type = "submit" value = "Mine!!" />
</form>
<script language="JavaScript" type="text/javascript">
    function parseLogs(text) {
        var re = new RegExp("^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$");
        var myArray = re.exec("text");
        document.write(myArray.toString());

    }
</script>
</center>
</body>
</html>

【问题讨论】:

  • 您现在的代码有什么问题?
  • 您肯定需要尝试正则表达式文字var re = /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/g;。并使用input.match(re)
  • @Reddy :它没有显示任何内容。它应该打印所有出现的地址
  • 您正在测试字符串“test”而不是给定变量
  • 删除^anchors$

标签: javascript regex


【解决方案1】:

我看到代码中有错字。

var myArray = re.exec("text"); 你只是在 string text

上运行正则表达式

应该是

var myArray = re.exec(text);变量 text

运行正则表达式

【讨论】:

  • 错字不是真正的问题。
  • 这没有用,但至少还有两个问题。
【解决方案2】:

你需要:

  • 使用正则表达式避免双反斜杠转义速记类(现在,"\." 转换为 .
  • 从模式中移除锚点(即^$
  • 向正则表达式添加全局修饰符 (/g)
  • 在正则表达式中使用String#match()(如果您不需要使用捕获组捕获的值,否则,您需要在循环中运行RegExp#exec 来收集这些值)。

function parseLogs(text) {
   var re = /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/g;
   var myArray = text.match(re);
   document.write("<pre>"+JSON.stringify(myArray, 0, 4) + "</pre>");
}
<h5>Paste your Apache log file in the box below and click on Mine!</h5>

<textarea  rows="5" cols="200" form="mine_log" id = "logs">
12.34.56.76
 45.45.34.24
</textarea>
<form id = "mine_log" method = "" onsubmit="parseLogs(document.getElementById('logs').value)">
    <input type = "submit" value = "Mine!!" />
</form>

请注意,如果您不需要捕获的值,您甚至可以从模式中删除 ()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    相关资源
    最近更新 更多