gran_profaci
gran_profaci

Reputation: 8461

Regex to split an array in Ruby based on Pattern

This is more of a "What regex do I use" rather than a semantics question.

I have the following string :

moneyString = "¥10,100 YEN,€100.00 EU,$100.00 US"

And I need to split it on the comma. However, I don't want the comma in the 10,000 Yen to be separated into two arrays.

Currently, if I do moneyString.split(',')

I get : [¥10, 100 YEN, €100.00 EU, $100.00 US] as the different array values. But I want :

[¥10100 YEN, €100.00 EU, $100.00 US]

Can someone show me how to get this regex correct? I'm sorry, but I am a complete newbie with this stuff.

Upvotes: 1

Views: 483

Answers (2)

undur_gongor
undur_gongor

Reputation: 15954

moneyString.split(/(?<!\d),/)

The keyword is "negative look-behind".

Upvotes: 1

Dani&#235;l Knippers
Dani&#235;l Knippers

Reputation: 3055

You could split on all commas that are NOT preceded by a number, using negative lookbehind.

moneyString = "¥10,100 YEN,€100.00 EU,$100.00 US"

puts moneyString.split(/(?<!\d),/)

# ¥10,100 YEN
# €100.00 EU
# $100.00 US

Upvotes: 6

Related Questions