开发者

Regexp to check for consecutive spaces

开发者 https://www.devze.com 2023-02-17 01:12 出处:网络
I\'m banging my head to the table in trying to write a regular expression that filter out strings that contain only Swedish letters, hyphens and single whitespaces - that is, n开发者_如何学运维ot two

I'm banging my head to the table in trying to write a regular expression that filter out strings that contain only Swedish letters, hyphens and single whitespaces - that is, n开发者_如何学运维ot two in a row. I've got this preg_match('/^[A-ZÅÄÖa-zåäö-]+\s{1}$/',$b) and I feel like I've tried a hundred different models, but it's not working. How would I accomplish this?


Multiple spaces (two or more) is {2,} so try to replace your {1} with that and run it again.


Often the best way to solve a problem like this is splitting it into two separate regular expression checks.

  • check that the string contains only the letters you want (and whitespaces)
  • if the first check passes, check that it doesn't have two or more consecutive spaces

Try:

if ( preg_match('/^[A-ZÅÄÖa-zåäö-\s]$/',$b) && !preg_match('/\s\s+/', $b) ) {
    /...
}


Right now, your regex looks for a word with those characters and then a single space. If you're looking for a way to capture things like [word][single space][word][single space], you may want to try

/^([A-ZÅÄÖa-zåäö-]+\s{1}?)+$/


I got an answer that worked perfectly, but it disappeared... Anyway, this code did the trick !preg_match('/^(?:[a-zåäö-]+|\s(?!\s))+$/i',$b)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号