Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def regex2post(regE): # Convert regular expression from infix to postfix
- precedenceMap = {
- '(' : 1,
- ')' : 1,
- '?' : 2,
- '*' : 2,
- '+' : 2,
- '.' : 3
- }
- postfix_reg = ''
- operator_stack = Stack()
- print(regE)
- for c in regE:
- if c.isalpha():
- postfix_reg += c
- elif (c == '*' or c == '+' or c == '?' or c == '.' or c == '(') and operator_stack.isEmpty():
- operator_stack.push(c)
- elif (c == '*' or c == '+' or c == '?' or c == '.' or c == '(' or c == ')') and not(operator_stack.isEmpty()):
- previous_operator = operator_stack.pop()
- print(previous_operator)
- if previous_operator != '(' and previous_operator != ')' and precedenceMap[previous_operator] >= precedenceMap[c]:
- postfix_reg += previous_operator
- operator_stack.push(c)
- if previous_operator == '(':
- operator_stack.push(previous_operator)
- operator_stack.push(c)
- if c == ')':
- previous_operator = operator_stack.pop()
- while not (previous_operator == '('):
- postfix_reg += previous_operator
- previous_operator = operator_stack.pop()
- while not(operator_stack.isEmpty()):
- postfix_reg += operator_stack.pop()
- return postfix_reg
Add Comment
Please, Sign In to add comment