Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match comma followed by whitespace?

Tags:

regex

ruby

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+)]/

like image 272
Kevin Avatar asked Jul 20 '11 03:07

Kevin


People also ask

How do you match a comma in regex?

The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ; . The closing ] indicates the end of the character set. The plus + indicates that one or more of the "previous item" must be present.

What does \b mean in regex?

The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).

What does \d mean in regex?

In regex, the uppercase metacharacter denotes the inverse of the lowercase counterpart, for example, \w for word character and \W for non-word character; \d for digit and \D or non-digit. The above regex matches two words (without white spaces) separated by one or more whitespaces.

What does \+ mean in regex?

Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol.


2 Answers

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"]
like image 123
Chris Jester-Young Avatar answered Sep 30 '22 15:09

Chris Jester-Young


You should just use:

,\s+

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

like image 37
paxdiablo Avatar answered Sep 30 '22 15:09

paxdiablo