4

I am trying to extract all IP addresses from an Apache log file input in the textarea field. I am using regular expressions for extracting the IP addresses. I want to see all the IP addresses printed on the screen. I cannot understand what I am doing wrong. Kindly help

<!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>
Anuvrat Tiku
  • 1,616
  • 2
  • 17
  • 25

2 Answers2

2

You need to:

  • Use a regex literal to avoid double backslash escaping the shorthand classes (right now, "\." translates into .)
  • Remove anchors from the pattern (i.e. the ^ and $)
  • Add a global modifier to the regex (/g)
  • Use a String#match() with the regex (in case you do not need the values captured with the capturing groups, else, you need to run the RegExp#exec inside a loop to collect those).

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>

Note that in case you need no captured values, you may even remove the ( and ) from your pattern.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

I see a typo in the code.

var myArray = re.exec("text"); you are just running the regex on the string text

should be

var myArray = re.exec(text); run the regex on the variable text

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59