[英]regex--how to match a parentheses followed by non-digit characters?
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
:我将字符串拆分为数组的方式是使用以下.match
:
const arr = string
.match(/\(\d+[^(]+/g)
});
The regex in .match
splits the large string of questions into an array of strings. .match
的正则表达式将大串问题拆分为一个字符串数组。 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?在这种情况下, .match 函数在 ( in (faa,它抛出数组。如何修改正则表达式以使其匹配左括号后跟无限数量的非括号字符) 处进行拆分,但是只要后面跟着一个非数字字符就匹配括号吗?
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.