删除逗号前的空格后的字符

时间:2013-09-12 22:15:24

标签: regex

我有一个字符串:

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

有没有办法可以使用正则表达式来提取空间右边的任何内容,包括逗号离开:

field1, field2, field3

我无法使用正确的正则表达式语法为我工作。

3 个答案:

答案 0 :(得分:5)

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

Regular expression visualization

Edit live on Debuggex

  • \w是一个字母数字字符(如果您想要除空格之外的任何字符,可以将其替换为[^ ]
  • +表示一个或多个字符
  • ?:使捕获组不是捕获组
  • ,|$表示字符串的结尾是,或行的结尾

注意: ()表示捕获组

请详细了解regex here并使用debugexx.com进行试验。

答案 1 :(得分:2)

  

有没有办法可以使用正则表达式来提取空间右边的任何内容,包括逗号...

您可以使用,的非捕获组或使用前瞻来执行此操作。

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

正则表达式:

(                 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

答案 2 :(得分:0)

 /[^ ]+(,|$)/ 

应该这样做。 (,|$)允许您在行中的最后一个条目没有逗号。