Artjom
Artjom

Reputation: 37

Regex to grab first and last number on each line

I'm stuck here...

So, I have a string:

6,5,1,0,0,4,0,2,1121,18,54,67,6,0
15,5,10,0,6,5,1,3,20,47,119,153,15,0
187,72,115,2,8,19,37,121,74,98,511,622,143,44

I need to get the first and last number of each row and put them into the table (with JavaScript).

As a result I need

<tr><td>6</td><td>0</td></tr>
<tr><td>15</td><td>0</td></tr>
<tr><td>187</td><td>44</td></tr>

Any help is appreciated. Maybe even a hint :)

Upvotes: 0

Views: 161

Answers (4)

Xotic750
Xotic750

Reputation: 23472

I would not use a regex for this problem but String.split instead, then do something like this.

HTML

<table id="results"></table>

Javascript

var table = document.getElementById("results"),
    strings = "6,5,1,0,0,4,0,2,1121,18,54,67,6,0\n15,5,10,0,6,5,1,3,20,47,119,153,15,0\n187,72,115,2,8,19,37,121,74,98,511,622,143,44".split("\n");

strings.forEach(function (string) {
    var tr = document.createElement("tr"),
        tdFirst = document.createElement("td"),
        tdLast = document.createElement("td"),
        array = string.split(",");

    tdFirst.textContent = array[0];
    tdLast.textContent = array[array.length - 1];

    tr.appendChild(tdFirst);
    tr.appendChild(tdLast);
    table.appendChild(tr);
});

On jsfiddle

Upvotes: 0

agarici
agarici

Reputation: 612

Hope this will help you

<script type="text/javascript">
function Test()
{
  var stringValue = "6,5,1,0,0,4,0,2,1121,18,54,67,6,0";
  stringValue = BuildRow(stringValue);  //stringValue = <tr><td>6</td><td>0</td></tr>
  alert(stringValue);
}

//Build a table row from string
function BuildRow(sValue)
{
   var first = GetFirstNumberOfLine(sValue);
   var last = GetLastNumberOfLine(sValue);
   var row = "<tr><td>" + first + "</td><td>" + last +  "</td></tr>";
   return row;
}

//Return The first number of a string
function GetFirstNumberOfLine(sValue)
{
     var numberArray = sValue.split(",");
     return  numberArray[0];
}

//Return The first last number of a string
function GetLastNumberOfLine(sValue)
{
     var numberArray = sValue.split(",");
     return numberArray[numberArray.length -1 ];
}
</script>

Upvotes: 0

Bemmu
Bemmu

Reputation: 18217

You can split the multiline string into lines with

x = "a\nb\nc"
lines = x.split("\n")

Loop through each line and use regexp to find the first and last digit. One easy to understand way is to use a separate one for the first and last.

var first = line.match(/^\d+/)[0]
var last = line.match(/\d+$/)[0]

Regexp isn't really necessary though, you could just use .split(',').

To make the table, I would suggest using jQuery and reading the jQuery docs for .append or google for something like "how to make table with jquery".

Upvotes: 0

DevZer0
DevZer0

Reputation: 13525

You can try the regexp

/^([0-9]+),[0-9,]+,([0-9]+)$/

Will give you a match for the first and last number

Upvotes: 1

Related Questions