0

I want to return an array for a table-row string like:

'31 Chicken   2013  "Chi cken"    12.345   ****'

to an array: ["Chicken", 2013, "Chi cken", 12.345, null]

  • The columns in the table are defined by any number of one or more spaces (non-tab) between entries. (Entries which contain spaces are enclosed in double quotes and cannot contain quotes themselves.)

  • The first column is always an integer, which can be discarded, so that the array begins with second column.

  • Entry can be an integer, float or string.

  • 4 consecutive asterisks **** denote a null value.

Any help?

(link to fuller format info: https://github.com/xoreos/xoreos-docs/blob/master/specs/bioware/2DA_Format.pdf)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
bladeo
  • 27
  • 4

3 Answers3

0

I would write a parser which covers your example.

Working example: JSFiddle

for (i = 0; i < tmp.length; i++) {
  if (i == 0) continue;
  else if (tmp[i] === "****") {
    output.push("null");
    continue;
  }
  else if (tmp[i].startsWith('"')) {
    output.push(tmp[i] + ' ' + tmp[i + 1]);
    i++;
    continue;
    }
  else {
    output.push(tmp[i]);
  }
}
KRONWALLED
  • 1,422
  • 11
  • 12
0

Here's the regex for the six matches, you can then forget the item [0] and convert the last one to null (when ****)

[0-9\.0-9]+|[a-zA-Z0-9]+|\"[a-zA-Z0-9 ]+\"|\*\*\*\*
Pietro
  • 988
  • 10
  • 19
0

I took some of KRONWALLED's suggestion and a regex from this answer. Couldn't figure out how to get quotes from being added to matched strings.

var str = '31 Chicken    2013 "Chi cken" 12.345 ****';
console.log(str);
var tmp = str.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g);
console.log(tmp);
var n;
tmp.shift();
for (i = 0; i < tmp.length; i++) {
  str = tmp[i];
  if (str === "****") {
    tmp[i] = null;
  }
  else if (str.startsWith('"')) {
    n = str.lastIndexOf('"');
    tmp[i] = str.slice(1,n); 
    }
  else {
    n = Number(str);
    if(isNaN(n)){
      //console.log(str + " NaN")
    }
    else tmp[i] = n;
  }

}
console.log(tmp);
Community
  • 1
  • 1
bladeo
  • 27
  • 4