0

I'm trying to capture aa,bb,cc from the following strings:

,aa,bb,cc,
aa,bb,cc,
,aa,bb,cc
aa,bb,cc

My plan was to:

  1. Match the start of line anchor, or the anchor followed by a comma
  2. Capture until the end of line anchor, or a comma followed by the end of line anchor

The closest I've got is: (?:^,|^)(.*)(?:$|,$), but that includes trailing commas in the capture group:

,aa,bb,cc, -> aa,bb,cc,
aa,bb,cc,  -> aa,bb,cc,
,aa,bb,cc  -> aa,bb,cc
aa,bb,cc   -> aa,bb,cc

Why isn't it working, and what's the right solution?

koi-feeding
  • 989
  • 1
  • 8
  • 9
  • You can probably do this with your language's `trim()` method (or equivalent). Certainly jQuery and PHP can take a parameter of characters to trim from the string (eg `$str = trim($str, ',')`) – Joe Feb 12 '12 at 21:48

2 Answers2

2

Try this

^,*(?<trimmed>.*?),*$
Terkel
  • 1,575
  • 8
  • 9
  • Thanks, that got it. For anyone else reading, the `?` is apparently [.NET's version of named-group syntax](http://www.regular-expressions.info/named.html). – koi-feeding Feb 12 '12 at 22:05
  • Heh, if I had recognized the named-group syntax, I would have realized my later answer was exactly the same as this. :) – Tim Goodman Feb 12 '12 at 22:16
1

This seems to work: ^,*(.*?),*$

The key idea is the lazy star *? because I want trailing commas (and even multiple trailing commas, I'm assuming) to be matched by the last ,* instead of being matched inside the parentheses.

Tim Goodman
  • 23,308
  • 7
  • 64
  • 83
  • However, I generally wouldn't use RegEx for this. As Joe mentioned, most languages have some kind of `trim` function already. Notably not JavaScript, unless you're using a framework that has it. – Tim Goodman Feb 12 '12 at 22:03