Home > Blockchain >  How to find the longest sequence of "broken" characters using Regex in JS?
How to find the longest sequence of "broken" characters using Regex in JS?

Time:02-16

I'm trying to find the longest sequence of "broken"(different from letter, digit, space) characters in this sentence:

'Tempera####&&#^ na @#$ata 23 grad#%&.'

I really want to do it using Regex, but I'm not that familiar with the usage of Regex in JS. I watched a lot of tutorials, also read bunch of articles and this is what I came up with:

let input = [
        'Tempera####&&#^ na @#$ata 23 grad#%&.'
];

let print = this.print || console.log;
let gets = this.gets || ((arr, index) => () => arr[index  ])(input, 0);

let message = gets();

//different from letter, digit, space

let counter = 1;
let allWords = /[a-z1-9\s]/gi;

for (let i = 0; i < message.length; i  ) {
  let current = message[i];
  // allWords.lastIndex = 0;
  let isExisting = allWords.test(current);

  if (current === '.') {
    break;
  }
  if (isExisting) {
    counter = 1;

  } else {
    counter  ;
  }


}

print(counter)

Here the answer should be 8 , because we have 8 consecutive symbols inside the word "Tempera####&&#^" , which are not letter, digit or space.

Unfortunately this doesn't work. I'm still trying to understand where is my mistake, so I'll be very thankful if someone can "show me the way".

CodePudding user response:

Use a regular expression that matches the opposite ([^.....]) and as many times as possible ( ). Then check the size of all matches and pick the longest length. As there is a special role for the point (which apparently is always at the end), consider it as not broken.

let allWords = /[^a-z1-9\s.] /gi;

let input = [
    'Tempera####&&#^ na @#$ata 23 grad#%&.'
];
for (let message of input) {
    let results = message.match(allWords) ?? [];
    let counter = Math.max(0, ...results.map(({length}) => length));
    console.log("longest", counter);
}

CodePudding user response:

const input = 'Tempera####&&#^ na @#$ata 23 grad#%&.';
function findLongestSubstring(input) {
  let longest = '';
  let current = '';
  for (let i = 0; i < input.length; i  ) {
    if (input[i].match(/[^a-zA-Z\d\s]/)) {
      current  = input[i];
    } else {
      if (current.length > longest.length) {
        longest = current;
      }
      current = '';
    }
  }
  return longest.length;
}
console.log(findLongestSubstring(input));

  • Related