Jeffrey Kramer
Jeffrey Kramer

Reputation: 1345

Remove characters after space before a comma

I have a string:

stuff.more AS field1, stuff.more AS field2, blah.blah AS field3

Is there a way I can use regex to extract anything to the right of a space, up-to and including a comma leaving:

field1, field2, field3

I cannot get the proper regex syntax to work for me.

Upvotes: 0

Views: 1892

Answers (3)

hwnd
hwnd

Reputation: 70732

Is there a way I can use regex to extract anything to the right of a space up-to and including a comma...

You could do this with either a non capturing group for your , or use a look ahead.

([^\s]+)(?=,|$)

Regular expression:

(                 group and capture to \1:
 [^\s]+           any character except: whitespace (\n,
                  \r, \t, \f, and " ") (1 or more times)
)                 end of \1
(?=               look ahead to see if there is:
  ,               a comma ','
  |               OR
  $               before an optional \n, and the end of the string
)                 end of look-ahead

Upvotes: 2

progrenhard
progrenhard

Reputation: 2363

(\w+)(?:,|$)

Regular expression visualization

Edit live on Debuggex

  • \w is a alphanumeric character (you can replace this with [^ ] if you want any character except a space)
  • + means one or more character
  • ?: makes a capture group not a capture group
  • ,|$ means the end of the string is either a , or the end of the line

note: () denotes a capture group

please read more about regex here and use debugexx.com to experiment.

Upvotes: 5

foundry
foundry

Reputation: 31745

 /[^ ]+(,|$)/ 

should do it. (,|$) allows for your last entry in the line without a comma.

Upvotes: 0

Related Questions