1

Input string is "F000668A - EED14F50 - 000EED1KFF0000000F03".

I want to print/save 4 characters after EED1. The number of EED1 can 1 or more. In the above example, the expected result is => 4F50,KFF0.

My code:

var input = "F000668A - EED14F50 - 000EED1kFF0000000F03"

const string = input.toLowerCase().replace(/\s/g, '').replace(/(\r\n|\n|\r)/gm, "");    //Lowercase it, delete spaces and linebreaks.

string.match(/eed1/g).forEach((element) => {
    console.log(element)
 });

Result:

eed1
eed1

But when I try to print further characters then the script print only 1 item.

string.match(/eed1(.*)/g)

Result:

eed14f50-000eed1kff0000000f03

How can I get the requested info with regex? (or an other way) Thank you in advance.

Denes
  • 111
  • 7

1 Answers1

1

You can use

const input = "F000668A - EED14F50 - 000EED1kFF0000000F03";
const matches = input.replace(/\s/g, '').matchAll(/eed1([a-z0-9]{4})/ig);
console.log(Array.from(matches, m => m[1]));

Note:

  • You do not need to replace line breaks separately from other whitespaces, \s matches \n, \r, and the rest of vertical whitesapce
  • There is no need to lowercase the input, you can use /i flag to match in a case insensitive way
  • /eed1([a-z0-9]{4})/ig will match all occurrences of eed1 (case insensitively) and then capture four letters/digits, and matchAll will ensure the access to all the capturing group values (match() discarded them all as the regex was built with the g flag).

See the regex demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thank you. One more question. How can I search for an other regex. How can I concatenate more regex? eg.: EED1(\w{4}) & 0F0 – Denes Jun 23 '21 at 13:10
  • @Dani Please provide an input string and requirements and expected output. If you need to use a variable in regex, see [How do you use a variable in a regular expression?](https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression). – Wiktor Stribiżew Jun 23 '21 at 13:39