0

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);
double-beep
  • 5,031
  • 17
  • 33
  • 41
  • Is your question how to extract the result of each line, or how to access the correctly extracted value, or something else? – VLAZ Jan 31 '23 at 10:41
  • 2
    If you want to extract names, why do you include the boolean value too. Is this needed? If just interested in names, perhaps use `^(?!Name|-)\S+`? – JvdV Jan 31 '23 at 10:41

3 Answers3

1

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);
I0_ol
  • 1,054
  • 1
  • 14
  • 28
0

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

AnArrayOfFunctions
  • 3,452
  • 2
  • 29
  • 66
0

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);
}