简体   繁体   English

正则表达式 - 字符串无法启动,以空格结尾并且由一行中的少量空格组成

[英]Regular expression - String cannot start, end with white-space and consist of few white-spaces in a row

I am looking for regular expression that allow strings that does not start and does not end with white-space and does not consist of few white-spaces in a row. 我正在寻找正则表达式,允许字符串不启动,不以空格结尾,并且不包含连续的少量空格。

Allow: 允许:

asd asd asd,
asdasd,
asd asd,

Disallow: 不允许:

asd   asdasd,
 asdasd,
asdasd  ,

A simple solution without look-ahead: 一个简单的解决方案,无需预测:

^\S+(?: \S+)*$

Demo on regex101 在regex101上演示

This solution will also match length 1 string like a . 此解决方案还将匹配长度为1的字符串,如a

I assume that you don't want to allow tabs or new line as the space character. 我假设你不想允许标签或新行作为空格字符。 Note that most solutions here don't take into account Unicode spaces, which you would have to manually specify to prevent their matches. 请注意,此处的大多数解决方案都没有考虑Unicode空间,您必须手动指定这些空间以防止它们匹配。

You can use this regex: 你可以使用这个正则表达式:

/^\S(?!.*\s{2}).*?\S$/

Explanation: 说明:

  • ^ line start ^行开始
  • \\S - match a non space at start \\S - 在开始时匹配非空格
  • (?!.*\\s{2}) negative lookahead to disallow 2 consecutive spaces (?!.*\\s{2})否定前瞻以禁止2个连续的空格
  • .*? - match any character (0 or more, non-greedy) - 匹配任何字符(0或更多,非贪婪)
  • \\S - match a non space at end \\S - 最后匹配非空格
  • $ - line end $ - 行结束

You can use the following 您可以使用以下内容

/((^[^\s]).*?([^\s]$))/

Edit: (Explanation,) 编辑:(解释)

^ match line start, ^匹配线开始,

[^\\s] match anything that is not a space [^\\s]匹配任何不是空格的东西

.*? match any character 匹配任何角色

$ match line end $ match line end

EDIT: 编辑:

if you want to remove the possibility of adjacent spaces from string you can use this regex. 如果你想从字符串中删除相邻空格的可能性,你可以使用这个正则表达式。

/((^(?!\s))(\w|\s(?!\s+))+((?<!\s)$))/

above regex may not work in javascript because of the negative lookbehind at the end but works fine for python. 以上正则表达式可能无法在javascript中工作,因为最后的负面看法,但对python工作正常。

^(?!.*[ ](?=[ ]))\S.*?\S$

Try this.See demo. 试试这个。看看演示。

https://regex101.com/r/vD5iH9/33 https://regex101.com/r/vD5iH9/33

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM