Может быть, здесь мы могли бы проигнорировать ( и ) и увидеть желаемый результат:
(.*?)(?:[()]|)
RegEx
Если это не было вашим желаемым выражением, вы можете изменить / изменить выражение в regex101.com .
RegEx Circuit
Вы также можете визуализировать свои выражения в jex.im :
JavaScript Demo
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 Test
# 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.
RegEx
Если вы хотите буквально проверить правильные ответы, вы можете сделать это слово за словом. Может быть, это выражение будет работать:
^((an|one)?(\s?)([aple]+)?(\s?)([devic]+)?)$
Python Code
Вы можете просто добавить 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]+)?)$
Это также передало бы некоторые слова с ошибками, которые, я думаю, были бы желательны. Если нет, вы можете просто удалить []
и использовать группы захвата с логическими ИЛИ:
(apple|orange|banana)?