【问题标题】:Regex to match spaces before comma but not after正则表达式匹配逗号之前的空格但不匹配之后
【发布时间】:2014-07-17 14:55:51
【问题描述】:

我想要一个正则表达式,它不允许逗号后有空格,但应该允许逗号前有空格。 逗号也应该是可选的。

我当前的正则表达式:

^[\w,]+$

我尝试在其中添加\s,也尝试了^[\w ,]+$,但这也允许逗号后有空格!

这应该是测试用例:

Hello World // true
Hello, World // false (space after comma)
Hello,World // true
Hello,World World // false

任何帮助将不胜感激!

【问题讨论】:

  • “不允许”不明确,具体是什么意思

标签: html regex text


【解决方案1】:

下面的正则表达式不允许逗号后有空格,

^[\w ]+(?:,[^ ]+)?$

DEMO

说明:

  • ^ 行首。
  • [\w ] 匹配单词字符或空格一次或多次。
  • (?:) 这称为非捕获组。该组内的任何内容都不会被捕获。
  • (?:,[^ ]+)? 逗号后跟任何非空格字符一次或多次。通过在非捕获组之后添加?,这告诉正则表达式引擎它是一个可选的。
  • $一行结束

【讨论】:

  • 完美!请添加说明:)
  • @imbondbaby Regex101 演示对正则表达式进行了解释。
  • 抱歉,不在 PC 附近……Regex101 希望我在查看他们的网站之前更新我的浏览器。
  • @imbondbaby 添加了解释。
  • 感谢@AvinashRaj。我试图解决这个问题好几个小时。
【解决方案2】:

我想这取决于你想做什么,如果你只是测试语法错误的存在,你可以使用类似的东西。

See this example here >

var patt = / ,/g; // or /\s,/g if you want
var str = 'Hello ,World ,World';
var str2 = 'Hello, World, World';
console.log( patt.test(str) ) // True, there are space before commas
console.log( patt.test(str2) ) // False, the string is OK!

前瞻很有用,但如果不了解基础知识就很难理解。

Use this site,它非常适合可视化您的正则表达式

【讨论】:

    【解决方案3】:

    你可以使用这个正则表达式。

    ^[\w ]+(?:,\S+)?$
    

    解释:

    ^          # the beginning of the string
    [\w ]+     # any character of: word characters, ' ' (1 or more times)
    (?:        # group, but do not capture (optional):
      ,        #   ','
      \S+      #   non-whitespace (all but \n, \r, \t, \f, and " ") (1 or more times)
    )?         # end of grouping
    $          # before an optional \n, and the end of the string
    

    【讨论】:

    • 它需要在逗号前留出空格,这样你的就不行了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多