Home > Software engineering >  Split long string delimited by spaces but avoid words that go together
Split long string delimited by spaces but avoid words that go together

Time:11-29

I have a long string delimited by spaces that I want to put in an array. The string always comes in the same format example

Player11 11 56789 londoncity London-Ciy user@londoncity QA_UK The problem I have is when index 4 comes with spaces for example

Player10 10 12345 mancity Manchester city Club user@mancity PROD_UK

I have tried

let inputValues = "Player11 11 56789 londoncity London-Ciy user@londoncity QA_UK"

var inputValuesParsed = inputValues.split(/(\s )/).filter( function(e) { return e.trim().length > 1; } );

It works fine the problem is with the string Player10 10 12345 mancity Manchester city Club user@mancity PROD_UK I want Manchester City Club to be in one index

CodePudding user response:

If you know how many data values are in a line, you can account for the value that may have spaces by making sure that what follows it contains exactly the desired number of data values and spaces, followed by the end of the line.

const inputValues = "Player10   10  12345 mancity   Manchester city Club user@mancity PROD_UK ";
const inputValuesParsed = inputValues
  .trim()
  .match(/^(\S )  (\S )  (\S )  (\S )  (\S.*)  (\S ) (\S )$/);
inputValuesParsed.shift(); // remove the first element - the whole match
console.log(inputValuesParsed);

The part that matches the city name - (\S.*) - will expand until what follows it - the 3 data values with no spaces inside them - are followed by the end of the line.

That said, it would be better to fix whatever's generating this input string so there's less ambiguity. For example, if it's being generated by JavaScript, better to use JSON.stringify. If it's from a spreadsheet, better to use a C

  • Related