Kevin
Kevin

Reputation: 635

Regex to match comma followed by whitespace?

I am trying to make a ruby regex to match tags in the format Toys, Cars, Some Other Topic but I can't figure out how to make it so that it splits it at after a comma and white space after but not if there is whitespace in a tag

This is what I have come up with http://rubular.com/r/ptjeQ1KyoD but is wrong for now.

/[\/,$\(\s+)]/

Upvotes: 7

Views: 29098

Answers (4)

Stephen M
Stephen M

Reputation: 181

You could use (/,/x) which split all strings with comma(,)

Check here

http://rubular.com/r/8XdjgLK19g

'Toys, Cars, Some Other Topic'.split(/,/x)
=> ["Toys", "Cars", "Some Other Topic"]

Upvotes: 0

Hrushi
Hrushi

Reputation: 307

function Validate(txt) { txt.value = txt.value.replace(/[^, a-zA-Z]+/g, ''); }

Upvotes: -1

paxdiablo
paxdiablo

Reputation: 882116

You should just use:

,\s+

This matches all commas followed by one or more whitespace characters, and doesn't match the spaces beyond Some.

Upvotes: 7

C. K. Young
C. K. Young

Reputation: 223133

You can just use /,\s*/ (which is much simpler than what you've got!):

'Toys, Cars, Some Other Topic'.split /,\s*/
=> ["Toys", "Cars", "Some Other Topic"]

Upvotes: 20

Related Questions