簡體   English   中英

單破折號電話號碼-正則表達式驗證

[英]Single dash phone number - regex validation

我需要一個簡單的正則表達式來驗證形式為xy的電話號碼,其中x和y可以表示任意數字,而破折號是可選的,但是如果確實顯示,則大多數出現在字符串中(破折號必須在數字處它的左和右)

/^\\d+(?:-\\d+)?$/應該可以解決問題。

/ ^ \\ d +(-\\ d +)?$ /)似乎有效。 它匹配一個或多個前導數字,並帶有可選的“連字符后跟一個或多個數字”。

#!/usr/bin/perl
#
@A = ( "1-2",
       "-12",
       "12-",
       "123-1234",
       "1-",
       "-1",
       "123",
       "1",
       "foo-bar",
       "12foo34",
       "foo12-34",
       "12f-o34",
       );

foreach (@A) {
  if (/^\d+(-\d+)?$/) {
    print "\"$_\" is a phone number\n";
  } else{
    print "\"$_\" is NOT a phone number\n";
  }
}

給出:

$ ./phone.pl 
"1-2" is a phone number
"-12" is NOT a phone number
"12-" is NOT a phone number
"123-1234" is a phone number
"1-" is NOT a phone number
"-1" is NOT a phone number
"123" is a phone number
"1" is a phone number
"foo-bar" is NOT a phone number
"12foo34" is NOT a phone number
"foo12-34" is NOT a phone number
"12f-o34" is NOT a phone number

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM