I am making a question database, and the way that I've made the database is by splitting a string into an array of smaller strings, where each is a question and its answer. For example, the string I have looks like
var string = "(1) foo? ANSWER: fee (2) fah. ANSWER: feh"
The way I'm splitting the string into the array is with the following .match
:
const arr = string
.match(/\(\d+[^(]+/g)
});
The regex in .match
splits the large string of questions into an array of strings. The way it is now, the match starts at a opening parenthesis of the number of a question and matches everything up until the next opening parenthesis, which is the start of the next question's number. So the resulting array looks like
["(1) foo? ANSWER: fee", "(2) fah. ANSWER: feh"]
This works perfectly fine except when the question itself has parentheses:
var string = "(1) foo foo (faa) foo? ANSWER: fee (2) fah. ANSWER: fah"
The .match function in this case makes a split at the ( in (faa, which throws off the array. How can I modify the regex expression so that it will match an opening parentheses followed by an infinite number of non-parentheses characters, but match a parentheses so long as it is followed by a non-digit character?
You could split using the position that asserts what is on the right are one or more digits between parenthesis.
(?=\(\d+\))
See a regex demo
var string = "(1) foo foo (faa) foo? ANSWER: fee (2) fah. ANSWER: fah" console.log(string.split(/(?=\\(\\d+\\))/g));
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.