也许,在这里我们可以忽略 ( 和 ) 并看到所需的输出:
(.*?)(?:[()]|)
正则表达式
如果这不是您想要的表达方式,您可以在regex101.com 中修改/更改您的表达方式。
正则表达式电路
你也可以在jex.im中可视化你的表情:
JavaScript 演示
const regex = /(.*?)(?:[()]|)/gm;
const str = `(an) apple (device)
apple device`;
const subst = `$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Python 测试
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"(.*?)(?:[()]|)"
test_str = ("(an) apple (device)\n"
"apple device")
subst = "\\1"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
正则表达式
如果您希望逐字检查正确答案,您可能需要逐字逐句进行。也许,这个表达式会起作用:
^((an|one)?(\s?)([aple]+)?(\s?)([devic]+)?)$
Python 代码
您可以简单地为匹配和不匹配添加if:
# -*- coding: UTF-8 -*-
import re
string = "an apple device"
expression = r'^((an|one)?(\s?)([aple]+)?(\s?)([devic]+)?)$'
match = re.search(expression, string)
if match:
print("YAAAY! \"" + match.group(1) + "\" is a match ??? ")
else:
print('? Sorry! No matches!')
输出
YAAAY! "an apple device" is a match ???
完整匹配和组的 JavaScript 演示
const regex = /^((an|one)?(\s?)([aple]+)?(\s?)([devic]+)?)$/gm;
const str = `an apple device
an apple
apple device
apple
one apple
one appl device
two apple deive
on apple device
a apple device`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
然后,您可以将任何其他您希望的字符添加到列表中,例如括号:
^(((one|an)+)?(\s?)([aple()]+)?(\s?)([()devic]+)?)$
这也会传递一些拼写错误的单词,我猜这是需要的。如果没有,您可以简单地删除 [] 并使用具有逻辑 OR 的捕获组:
(apple|orange|banana)?