+ оператор переписывает вместо конкатенации строк в Javascript - PullRequest
0 голосов
/ 04 июля 2019

Я пытаюсь получить строки из строкового параметра и скопировать их в новую строковую переменную.Эта логика будет выполняться до тех пор, пока новая строка не будет соответствовать определенному выражению регулярного выражения.

По какой-то (неизвестной мне) причине вывод - это то, что я ожидал ....

Это код:

matchRegexExp(log: string) {

            let regexString = /(?:\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})[\s\S]+?((?=\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})|$)/g;

            return log.match(regexString);
        }
}

private createString(string1: string) {

        let i: number = 0;
        let readLine: string[] = string1.split('\n');
        let x: string ='';

        while (this.matchRegexExp(readLine[i]) == null) {

            console.log('regex expression returns... ' + this.matchRegexExp(readLine[i]));
            console.log('current line content is... ', readLine[i]);
            console.log('x is = ', x);

            x = x + readLine[i];

            console.log('new x is ',x , '\n');
            i++;
        }
        console.log('final x is = ', x, '\n');

        return x;
    }

Это данные из строки1:

ana
has
apples
and 
  oranges
2019-01-01 11:11:11 INFO ThisApp - Started App

Строки, которые не соответствуют моему выражению регулярного выражения и которые должны быть скопированы в строку,:

ana
has
apples
and 
  oranges

Но когда я запускаю код ... я получаю этот "странный" вывод:

regex expression returns... null
current line content is...  ana
x is =
 ew x is  ana

regex expression returns... null
current line content is...  has
x is =  ana
 as x is  ana

regex expression returns... null
current line content is...  apples
hass =  ana
 pplesis  ana

regex expression returns... null
current line content is...  and
apples  ana
 nd esis  ana

regex expression returns... null
current line content is...    oranges
and es  ana
  oranges ana

  orangess =  ana

Ответы [ 2 ]

1 голос
/ 04 июля 2019

Мне кажется, что это проблема CRLF. Вы разделяете входную строку на \ n. Однако, если во входной строке есть разделители строк '\ r \ n' (так как данные, поступающие из Windows, вероятно, будут), то вы получите x, содержащий что-то вроде:

ana\rhas\rapples\r\rand \roranges

, который при распечатке будет выглядеть очень странно ('\ r' вернет курсор в начало строки).

Попробуйте разбить входную строку на '\ r \ n' и посмотрите, поможет ли это.

В качестве альтернативы, когда вы создаете 'x', вы можете снова добавить '\ n', чтобы получить многострочную строку:

x = x + readLine[i] + '\n';
0 голосов
/ 04 июля 2019

Я думаю, что вы печатаете неправильно.Вам нужно console.log('new x is ' + x + '\n).Пожалуйста, проверьте console.log документацию .

Я попробовал ваш код - немного измененную версию (с использованием проекта простого узла JS):

function matchRegexExp(log) {
  let regexString = /(?:\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})[\s\S]+?((?=\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})|$)/g;

  return log.match(regexString);
}

function createString(string1) {
  console.log("Value of string1 is:");
  console.log(string1);
  console.log()

  let i = 0;
  let readLine = string1.split('\n');
  let x ='';

  while (i < readLine.length) {
    if (matchRegexExp(readLine[i]) === null) {
      console.log('regex expression returns... ' + matchRegexExp(readLine[i]));
      console.log('current line content is... ', readLine[i]);
      console.log('x is = ' + x);

      x = x + readLine[i];

      console.log('new x is ' + x + '\n');
    }
    i++;
  }
  console.log('final x is = '+  x + '\n');

  return x;
}


const testString = `ana
has
apples
and 
  oranges
2019-01-01 11:11:11 INFO ThisApp - Started App`;

createString(testString);

Я получил этораспечатка:

Value of string1 is:
ana
has
apples
and 
  oranges
2019-01-01 11:11:11 INFO ThisApp - Started App

regex expression returns... null
current line content is...  ana
x is = 
new x is ana

regex expression returns... null
current line content is...  has
x is = ana
new x is anahas

regex expression returns... null
current line content is...  apples
x is = anahas
new x is anahasapples

regex expression returns... null
current line content is...  and 
x is = anahasapples
new x is anahasapplesand 

regex expression returns... null
current line content is...    oranges
x is = anahasapplesand 
new x is anahasapplesand   oranges

final x is = anahasapplesand   oranges

Хочу отметить, что я использую файл CRLF.

Это тот результат, к которому вы стремились?

...