Различные функции вывода в зависимости от порядка функций - PullRequest
1 голос
/ 14 июня 2019

Я тренируюсь с регулярными выражениями. Я нашел отличный ответ здесь, на StackOverflow: Как получить все совпадения для регулярного выражения в JavaScript?

Я скопировал код из проверенного ответа и вставил его в редактор, а затем написал свою собственную функцию, используя его. Итак, вот мой файл JS:

const regex = /[a-zA-Z]/g;
const _string = "++a+b+c++";

//The following is the loop from the StackOverflow user

var m;
do {
  m = regex.exec(_string);
  if (m) {
    // Logging the results
    console.log(m, "hello");
  }
} while (m);

console.log("Separating top and bottom so it's easier to read");
// Now here is the function I wrote using that code

const match = str => {
  let _matches;
  do {
    _matches = regex.exec(_string);
    if (_matches) {
      // Logging the results
      console.log(_matches);
    }
  } while (_matches);
}

match(_string);

Вот моя проблема: когда я запускаю этот код (это Repl.it), результаты первой функции (так что в этом случае цикл от пользователя stackoverflow) не включают первое совпадение, возвращаемое из RegExp.prototype.exec () метод. Вот мой вывод консоли:

 node v10.15.2 linux/amd64

 [ 'b', index: 4, input: '++a+b+c++', groups: undefined ] 'hello'
 [ 'c', index: 6, input: '++a+b+c++', groups: undefined ] 'hello'
 Separating top and bottom so it's easier to read
 [ 'a', index: 2, input: '++a+b+c++', groups: undefined ]
 [ 'b', index: 4, input: '++a+b+c++', groups: undefined ]
 [ 'c', index: 6, input: '++a+b+c++', groups: undefined ]

И если я переключу порядок цикла и функции, функция не вернет первое совпадение, а цикл вернет все три.

Любая помощь будет высоко ценится!

Ответы [ 2 ]

1 голос
/ 15 июня 2019

Я предполагаю, что мы можем иметь дело со строками, и мы хотим получить числовой индекс, где присутствует ++a+b+c++, что, вероятно, сработает это выражение:

index:\s*([0-9]+)\s*,.+'(\+\+a\+b\+c\+\+)'

Демо 1

const regex = /index:\s*([0-9]+)\s*,.+'(\+\+a\+b\+c\+\+)'/gm;
const str = `node v10.15.2 linux/amd64

 [ 'b', index: 4, input: '++a+b+c++', groups: undefined ] 'hello'
 [ 'c', index: 6, input: '++a+b+c++', groups: undefined ] 'hello'
 Separating top and bottom so it's easier to read
 [ 'a', index: 2, input: '++a+b+c++', groups: undefined ]
 [ 'b', index: 4, input: '++a+b+c++', groups: undefined ]
 [ 'c', index: 6, input: '++a+b+c++', groups: undefined ]`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Или, если мы просто хотим получить только индексы,

index:\s*([0-9]+)\s*,

const regex = /index:\s*([0-9]+)\s*,/gm;
const str = `node v10.15.2 linux/amd64

 [ 'b', index: 4, input: '++a+b+c++', groups: undefined ] 'hello'
 [ 'c', index: 6, input: '++a+b+c++', groups: undefined ] 'hello'
 Separating top and bottom so it's easier to read
 [ 'a', index: 2, input: '++a+b+c++', groups: undefined ]
 [ 'b', index: 4, input: '++a+b+c++', groups: undefined ]
 [ 'c', index: 6, input: '++a+b+c++', groups: undefined ]`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Демо 2

1 голос
/ 14 июня 2019

Если вы хотите получать только буквы из sttring, вам не нужен цикл.
Вы можете сделать

"++a+b+c+A+".match(/[a-z]/gi)
...