简体   繁体   中英

Using a Regular Expression how can i find if a string contains all the characters of a specific sequence in the correct sequence order?

Using a javascript Regular Expression how can i find if a string contains all the characters of a specific sequence in the correct sequence order?

For example, say i had the following string

sbvykkjwkkkTjSwbpvkoSbjpobvvwwEjknbnjsksbwybwSojoybryrbevvydTeydk

I want to check if it contains the following characters: TEST in that order but not necessarily next to each other.

 let reg = /.*T.*E.*S.*T.*/ let check = reg.test('sbvykkjwkkkTjSwbpvkoSbjpobvvwwEjknbnjsksbwybwSojoybryrbevvydTeydk') console.log(check)

You would use the "0 or more" wildcard pattern: .* . This will test for zero or more of any character. Then just order the test string with those in between.

Edit

If you want the pattern not to match when any other characters from the test string match out of order, then you should specify which "any" character could be in between the test characters, as in, "besides which characters are valid padding?".

 const positiveString = 'sbvykkjwkkkTjwbpvkobjpobvvwwEjknbnjsksbwybwSojoybryrbevvydTeydk'; const negativeString1 = 'sbvykkjwkkkTjwbpvkobSjpobvvwwEjknbnjsksbSwybwSojoybryrSbevvydTeydk'; const negativeString2 = 'asdfasdfasdfTasfasfdasfdSasfasfasdfasdfasfdEasdfaTsdfasdf'; const regex = /T[^TEST]*?E[^TEST]*?S[^TEST]*?T/; const match = positiveString.match(regex); const noMatch1 = negativeString1.match(regex); const noMatch2 = negativeString2.match(regex); console.log('Match: ', match, '\\nNo-match: ', noMatch1, '\\nAlso No-match: ', noMatch2);

Intercalate .* between your characters to match anything in between.

You make a generic function that generates a tester function like this:

 const testSequence = pattern => str => new RegExp(pattern.split('').join('.*')).test(str); const tester1 = testSequence('TEST'); const tester2 = testSequence('HELLO'); console.log(tester1('sbvykkjwkkkTjSwbpvkoSbjpobvvwwEjknbnjsksbwybwSojoybryrbevvydTeydk')); console.log(tester1('TEST')); console.log(tester1('TNT')); console.log(tester2('HhEeLlLlOo'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM