#python #regex
Вопрос:
Я хочу получить некоторые закономерности в математическом выражении.
Эти шаблоны имеют такую форму : «1.e10» или «1.e7» (где 1.e означает 10^blabla) Я хочу не только распознать эти шаблоны, но и заставить свой алгоритм возвращать числа (здесь 10 или 7).
Поэтому я попробовал это :
pattern = re.compile("1.e(d)*")
pattern.search(my expression)
Но я не понимаю, как получить цифры
Какая-нибудь помощь ?
Ответ №1:
regx, как это
"1.e(d*)"
Комментарии:
1. Хотя этот код может ответить на вопрос, предоставление дополнительного контекста относительно того, как и/или почему он решает проблему, повысит долгосрочную ценность ответа.
Ответ №2:
Предполагая, что вы хотите извлечь показатель экспоненциальной записи, не могли бы вы, пожалуйста, попробовать что-то вроде:
import re
l = ['1.e10', '1.e7', '2.0E 8', '3.58e-5'] # example inputs
for i in l:
m = re.search(r'd.d*[eE]([ -]?d )', i)
print(m.group(1)) # print the exponent
Выход:
10
7
8
-5
Ответ №3:
Воспользуйся
(?P<main>-?d (?:.d*)?)(?:[eE](?P<exponent>[ -]?d ))?
См.Доказательство регулярного выражения.
объяснение
--------------------------------------------------------------------------------
( group and capture to 1:
--------------------------------------------------------------------------------
-? '-' (optional (matching the most amount
possible))
--------------------------------------------------------------------------------
d digits (0-9) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
. '.'
--------------------------------------------------------------------------------
d* digits (0-9) (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
) end of 1
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
[eE] any character of: 'e', 'E'
--------------------------------------------------------------------------------
( group and capture to 2:
--------------------------------------------------------------------------------
[ -]? any character of: ' ', '-' (optional
(matching the most amount possible))
--------------------------------------------------------------------------------
d digits (0-9) (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
) end of 2
--------------------------------------------------------------------------------
)? end of grouping
import re
test_str = '1.e10, 1.e7, 2.0E 8, 3.58e-5'
matches = re.finditer(r'(?P<main>-?d (?:.d*)?)(?:[eE](?P<exponent>[ -]?d ))?', test_str)
print([m.groupdict() for m in matches])
Результаты: [{'main': '1.', 'exponent': '10'}, {'main': '1.', 'exponent': '7'}, {'main': '2.0', 'exponent': ' 8'}, {'main': '3.58', 'exponent': '-5'}]