Home > OS >  How can I extract a specific column from a string table?
How can I extract a specific column from a string table?

Time:01-31

I have a text. How I can extract the Name column with JavaScript and RegExp? I have a code but that doesn't work correctly

const stdout = 
`Name               Enabled Description
----               ------- -----------
6ytec              True
DefaultAccount     False   Some text.
John               True
WDAGUtilityAccount False   Some text
Admin              False   Some text
Guest              False   Some text`

const regexp = new RegExp("([а-яА-Яa-zA-Z_0-9] )\\s (True|False)\\s ");
let result = stdout.match(regexp);
console.log(result);

CodePudding user response:

An alternate approach without regex:

const stdout = 
`Name               Enabled Description
----               ------- -----------
6ytec              True
DefaultAccount     False   Some text.
John               True
WDAGUtilityAccount False   Some text
Admin              False   Some text
Guest              False   Some text`


const firstColumn = stdout
  .split('\n')
  .map(line => line.split(' '))
  .map(word => word[0])
  .slice(2)

console.log(firstColumn);

CodePudding user response:

You can use the following:

[...stdout.matchAll(/^(?!----|Name\b)\S \b/gm)]

^ - Matches beginning of line

(?! - Negative lookahead

| - or

\S - non white space

And \b means boundary between non character (i.e. when the non white spaces end)

/gm - means global and multiline

CodePudding user response:

i found solution! Thanks for talking about "group":

console.log(stdout);
const regexp = new RegExp("(?<name>([а-яА-Яa-zA-Z_0-9] ))\\s (True|False)\\s ", "mg");
for (const match of stdout.matchAll(regexp)) {
  console.log(match.groups.name);
}
  • Related