If you use match in the following regular expressions, the program will not end running.

Asked 2 years ago, Updated 2 years ago, 83 views

Hello, thank you for your continuous support.

I am writing a program that uses regular expressions in javascript, but the program doesn't work.

When I tried it, the following code encountered the same situation:

let regex=/(\w+(,|\s)*)+;/;
let text = "XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX";

// Freeze here
let matched = text.match(regex);

console.log (matched [0]);

In the case of this code, text does not end in semicolon, so I thought there was no match and matched would be null, but the program did not complete.

Could you tell me why this happened?

Thank you for your cooperation.

javascript node.js regular-expression

2022-09-30 19:26

1 Answers

There must be a combination explosion.

regex=/(\w+(,|\s)*)+;/

In , null with or without , but because it is at the end of the regex expression, the computer creates a pattern for the previous (\w+(,|\s)*)+ part, and then considers the pattern to see if it matches the given string for the first time.

In particular, (,|\s)* may or may not have a word delimiter, which is one of the reasons for the combination explosion.(,|\s)+ always determines a partial match for each XXXX,.So I would do this myself:

let regex=/(\w+(,|\s)+)+(\w+);/;

When I tried ideone, it ended successfully with null.


2022-09-30 19:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.