user10598651
user10598651

Reputation:

How to split and keep numbers together

I am programming a math expression checker. I have this string:

Oper = "((234+332)+(cos4-sin65))"

I want to split this string by separating all "()"s and operators minus numbers or trigonometric ratios to get this result:

Oper = ['(', '(', '234', '+', '332', ')', '+', '(', 'cos4', '-', 'sin65', ')', ')']

How would the split be?

Upvotes: 0

Views: 79

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

oper = "((234+332)+(cos4-sin65))"

oper.scan /[^[:alnum:]]|[[:alnum:]]+/
  #=> ["(", "(", "234", "+", "332", ")", "+", "(", "cos4", "-", "sin65", ")", ")"]

Scan for one non-alphanumeric character or one or more alphanumeric characters.

Upvotes: 1

Marcin Kołodziej
Marcin Kołodziej

Reputation: 5313

"((234+332)+(cos4-sin65))".split /([[:alpha:]]*\d+)*/
# => ["(", "(", "234", "+", "332", ")", "+", "(", "cos4", "-", "sin65", ")", ")"]

Splits the whole string by nothing or optional alphanumeric + digits.

Upvotes: 1

Related Questions