Python3 與 C# 基礎語法對比(String專欄)

 

Code:https://github.com/lotapp/BaseCodehtml

多圖舊排版:http://www.javashuo.com/article/p-nktbmdez-g.htmlpython

在線編程:https://mybinder.org/v2/gh/lotapp/BaseCode/masterlinux

在線預覽:http://github.lesschina.com/python/base/pop/2.str.htmlgit

Python設計的目的就是 ==> 讓程序員解放出來,不要過於關注代碼自己程序員

步入正題:歡迎提出更簡單或者效率更高的方法github

基礎系列:(這邊重點說說Python,上次講過的東西我就一筆帶過了)編程

1.基礎回顧

1.1.輸出+類型轉換

In [1]:
user_num1=input("輸入第一個數:")
user_num2=input("輸入第二個數:")

print("兩數之和:%d"%(int(user_num1)+int(user_num2)))
 
輸入第一個數:1
輸入第二個數:2
兩數之和:3
 

1.2.字符串拼接+拼接輸出方式

In [2]:
user_name=input("輸入暱稱:")
user_pass=input("輸入密碼:")
user_url="192.168.1.121"

#拼接輸出方式一:
print("ftp://"+user_name+":"+user_pass+"@"+user_url)

#拼接輸出方式二:
print("ftp://%s:%s@%s"%(user_name,user_pass,user_url))
 
輸入暱稱:tom
輸入密碼:1379
ftp://tom:1379@192.168.1.121
ftp://tom:1379@192.168.1.121
 

2.字符串遍歷、下標、切片

2.1.Python

重點說下python下標,有點意思,最後一個元素,咱們通常都是len(str)-1,他能夠直接用-1,倒2天然就是-2api

最後一個元素:user_str[-1]數組

user_str[-1]app

user_str[len(user_str)-1] #其餘編程語言寫法

倒數第二個元素:user_str[-2]

user_str[-1]

user_str[len(user_str)-2] #其餘編程語言寫法

In [3]:
user_str="七大姑曰:工做了嗎?八大姨問:買房了嗎?異性說:結婚了嗎?"
In [4]:
#遍歷
for item in user_str:
    print(item,end=" ") # 不換行,以「 」方式拼接
 
七 大 姑 曰 : 工 做 了 嗎 ? 八 大 姨 問 : 買 房 了 嗎 ? 異 性 說 : 結 婚 了 嗎 ? 
In [5]:
#長度:len(user_str)
len(user_str)
 
29
In [6]:
# #第一個元素:user_str[0]
user_str[0]
Out[6]:
'七'
In [7]:
# 最後一個元素:user_str[-1]
print(user_str[-1])
print(user_str[len(user_str)-1])#其餘編程語言寫法
 
?
?
In [8]:
#倒數第二個元素:user_str[-2]
print(user_str[-2])
print(user_str[len(user_str)-2])#其餘編程語言寫法
 
嗎
嗎
 

python切片語法[start_index:end_index:step]end_index取不到

eg:str[1:4] 取str[1]、str[2]、str[3]

eg:str[2:] 取下標爲2開始到最後的元素

eg:str[2:-1] 取下標爲2~到倒數第二個元素(end_index取不到)

eg:str[1:6:2] 隔着取~str[1]、str[3]、str[5](案例會詳細說)

eg:str[::-1] 逆向輸出(案例會詳細說)

In [9]:
it_str="我愛編程,編程愛它,它是程序,程序是誰?"
In [10]:
# eg:取「編程愛它」 it_str[5:9]
print(it_str[5:9])
print(it_str[5:-11]) # end_index用-xx也同樣
print(it_str[-15:-11])# start_index用-xx也能夠
 
編程愛它
編程愛它
編程愛它
In [11]:
# eg:取「編程愛它,它是程序,程序是誰?」 it_str[5:]
print(it_str[5:])# 不寫默認取到最後一個
 
編程愛它,它是程序,程序是誰?
In [12]:
# eg:一個隔一個跳着取("我編,程它它程,序誰") it_str[0::2]
print(it_str[0::2])# step=△index(eg:0,1,2,3。這裏的step=> 2-0 => 間隔1)
 
我編,程它它程,序誰
In [13]:
# eg:倒序輸出 it_str[::-1]
# end_index不寫默認是取到最後一個,是正取(從左往右)仍是逆取(從右往左),就看step是正是負
print(it_str[::-1])
print(it_str[-1::-1])# 等價於上一個
 
?誰是序程,序程是它,它愛程編,程編愛我
?誰是序程,序程是它,它愛程編,程編愛我
 

2.2.CSharp

此次爲了更加形象對比,一句一句翻譯成C#

有沒有發現規律,user_str[user_str.Length-1]==> -1是最後一個

user_str[user_str.Length-2]==> -2是最後第二個

python的切片其實就是在這方面簡化了

In [1]:
%%script csharp
//# # 字符串遍歷、下標、切片
//# user_str="七大姑曰:工做了嗎?八大姨問:買房了嗎?異性說:結婚了嗎?"
var user_str = "七大姑曰:工做了嗎?八大姨問:買房了嗎?異性說:結婚了嗎?";

//# #遍歷
//# for item in user_str:
//#     print(item,end=" ")
foreach (var item in user_str)
{
    Console.Write(item);
}

//# #長度:len(user_str)
//# print(len(user_str))
Console.WriteLine(user_str.Length);

//# #第一個元素:user_str[0]
//# print(user_str[0])
Console.WriteLine(user_str[0]);

//# #最後一個元素:user_str[-1]
//# print(user_str[-1])
//# print(user_str[len(user_str)-1])#其餘編程語言寫法
Console.WriteLine(user_str[user_str.Length - 1]);
//
//# #倒數第二個元素:user_str[-2]
//# print(user_str[-2])
Console.WriteLine(user_str[user_str.Length - 2]);
 
七大姑曰:工做了嗎?八大姨問:買房了嗎?異性說:結婚了嗎?29
七
?
嗎
 

其實你用Python跟其餘語言對比反差更大,net真的很強大了。

補充(對比看就清楚Pythonstep爲何是2了,i+=2==>2)

In [2]:
%%script csharp
//# 切片:[start_index:end_index:step] (end_index取不到)
//# eg:str[1:4] 取str[1]、str[2]、str[3]
//# eg:str[2:] 取下標爲2開始到最後的元素
//# eg:str[2:-1] 取下標爲2~到倒數第二個元素(end_index取不到)
//# eg:str[1:6:2] 隔着取~str[1]、str[3]、str[5](案例會詳細說)
//# eg:str[::-1] 逆向輸出(案例會詳細說,)
//
var it_str = "我愛編程,編程愛它,它是程序,程序是誰?";
//
//#eg:取「編程愛它」 it_str[5:9]
//            print(it_str[5:9])
//            print(it_str[5:-11]) #end_index用-xx也同樣
//            print(it_str[-15:-11])#start_index用-xx也能夠

//Substring(int startIndex, int length)
Console.WriteLine(it_str.Substring(5, 4));//第二個參數是長度

//
//#eg:取「編程愛它,它是程序,程序是誰?」 it_str[5:]
//            print(it_str[5:])#不寫默認取到最後一個
Console.WriteLine(it_str.Substring(5));//不寫默認取到最後一個

//#eg:一個隔一個跳着取("我編,程它它程,序誰") it_str[0::2]
//            print(it_str[0::2])#step=△index(eg:0,1,2,3。這裏的step=> 2-0 => 間隔1)

//這個我第一反應是用linq ^_^
for (int i = 0; i < it_str.Length; i += 2)//對比看就清除Python的step爲何是2了,i+=2==》2
{
    Console.Write(it_str[i]);
}

Console.WriteLine("\n倒序:");
//#eg:倒序輸出 it_str[::-1]
//# end_index不寫默認是取到最後一個,是正取(從左往右)仍是逆取(從右往左),就看step是正是負
//            print(it_str[::-1])
//            print(it_str[-1::-1])#等價於上一個
for (int i = it_str.Length - 1; i >= 0; i--)
{
    Console.Write(it_str[i]);
}
//其實能夠用Linq:Console.WriteLine(new string(it_str.ToCharArray().Reverse().ToArray()));
 
編程愛它
編程愛它,它是程序,程序是誰?
我編,程它它程,序誰
倒序:
?誰是序程,序程是它,它愛程編,程編愛我
 

3.Python字符串方法系列

3.1.Python查找

find,rfind,index,rindex

Python查找 推薦你用findrfind

In [3]:
test_str = "ABCDabcdefacddbdf"
# 查找:find,rfind,index,rindex
# xxx.find(str, start, end)
print(test_str.find("cd"))#從左往右
print(test_str.rfind("cd"))#從右往左
print(test_str.find("dnt"))#find和rfind找不到就返回-1
 
6
11
-1
In [4]:
# index和rindex用法和find同樣,只是找不到會報錯(之後用find系便可)
print(test_str.index("dnt"))
 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-cc6e22ad9acc> in <module>()
      1 # index和rindex用法和find同樣,只是找不到會報錯(之後用find系便可)
----> 2print(test_str.index("dnt"))

ValueError: substring not found
 

3.2.Python計數

python:xxx.count(str, start, end)

In [5]:
# 計數:count
# xxx.count(str, start, end)
print(test_str.count("d"))#4
print(test_str.count("cd"))#2
 
4
2
 

3.3.Python替換

Python:xxx.replace(str1, str2, 替換次數)

In [6]:
# 替換:replace
# xxx.replace(str1, str2, 替換次數)

print(test_str)
print(test_str.replace("b","B"))#並無改變原字符串,只是生成了一個新的字符串
print(test_str)
 
ABCDabcdefacddbdf
ABCDaBcdefacddBdf
ABCDabcdefacddbdf
In [7]:
# replace能夠指定替換幾回
print(test_str.replace("b","B",1))#ABCDaBcdefacddbdf
 
ABCDaBcdefacddbdf
 

3.4.Python分割

split(按指定字符分割),splitlines(按行分割)

partition(以str分割成三部分,str前,str和str後),rpartition(從右邊開始)

說下 split的切片用法print(test_input.split(" ",3)) 在第三個空格處切片,後面的不切了

In [9]:
# 分割:split(按指定字符分割),splitlines(按行分割),partition(以str分割成三部分,str前,str和str後),rpartition
test_list=test_str.split("a")#a有兩個,按照a分割,那麼會分紅三段,返回類型是列表(List),而且返回結果中沒有a
print(test_list)
 
['ABCD', 'bcdef', 'cddbdf']
In [10]:
test_input="hi my name is dnt"
print(test_input.split(" ")) #返回列表格式(後面會說)['hi', 'my', 'name', 'is', 'dnt']
print(test_input.split(" ",3))#在第三個空格處切片,後面的無論了
 
['hi', 'my', 'name', 'is', 'dnt']
['hi', 'my', 'name', 'is dnt']
 

繼續說說splitlines(按行分割),和split("\n")的區別:

In [11]:
# splitlines()按行分割,返回類型爲List
test_line_str="abc\nbca\ncab\n"
print(test_line_str.splitlines())#['abc', 'bca', 'cab']
print(test_line_str.split("\n"))#看出區別了吧:['abc', 'bca', 'cab', '']
 
['abc', 'bca', 'cab']
['abc', 'bca', 'cab', '']
In [12]:
# splitlines(按行分割),和split("\n")的區別沒看出來就再來個案例
test_line_str2="abc\nbca\ncab\nLLL"
print(test_line_str2.splitlines())#['abc', 'bca', 'cab', 'LLL']
print(test_line_str2.split("\n"))#再提示一下,最後不是\n就和上面同樣效果
 
['abc', 'bca', 'cab', 'LLL']
['abc', 'bca', 'cab', 'LLL']
 

擴展:split(),默認按 空字符切割(空格、\t、\n等等,不用擔憂返回'')

In [13]:
# 擴展:split(),默認按空字符切割(空格、\t、\n等等,不用擔憂返回'')
print("hi my name is dnt\t\n  m\n\t\n".split())
 
['hi', 'my', 'name', 'is', 'dnt', 'm']
 

最後說一下partitionrpartition: 返回是元祖類型(後面會說的)

方式和find同樣,找到第一個匹配的就罷工了【注意一下沒找到的狀況

In [14]:
# partition(以str分割成三部分,str前,str和str後)
# 返回是元祖類型(後面會說的),方式和find同樣,找到第一個匹配的就罷工了【注意一下沒找到的狀況】

print(test_str.partition("cd"))#('ABCDab', 'cd', 'efacddbdf')
print(test_str.rpartition("cd"))#('ABCDabcdefa', 'cd', 'dbdf')
print(test_str.partition("感受本身萌萌噠"))#沒找到:('ABCDabcdefacddbdf', '', '')
 
('ABCDab', 'cd', 'efacddbdf')
('ABCDabcdefa', 'cd', 'dbdf')
('ABCDabcdefacddbdf', '', '')
 

3.5.Python字符串鏈接

join :"-".join(test_list)

In [15]:
# 鏈接:join
# separat.join(xxx)
# 錯誤用法:xxx.join("-")
print("-".join(test_list))
 
ABCD-bcdef-cddbdf
 

3.6.Python頭尾判斷

startswith(以。。。開頭),endswith(以。。。結尾)

In [16]:
# 頭尾判斷:startswith(以。。。開頭),endswith(以。。。結尾)
# test_str.startswith(以。。。開頭)
start_end_str="http://www.baidu.net"
print(start_end_str.startswith("https://") or start_end_str.startswith("http://"))
print(start_end_str.endswith(".com"))
 
True
False
 

3.7.Python大小寫系

lower(字符串轉換爲小寫),upper(字符串轉換爲大寫)

title(單詞首字母大寫),capitalize(第一個字符大寫,其餘變小寫)

In [17]:
# 大小寫系:lower(字符串轉換爲小寫),upper(字符串轉換爲大寫)
# title(單詞首字母大寫),capitalize(第一個字符大寫,其餘變小寫)

print(test_str)
print(test_str.upper())#ABCDABCDEFACDDBDF
print(test_str.lower())#abcdabcdefacddbdf
print(test_str.capitalize())#第一個字符大寫,其餘變小寫
 
ABCDabcdefacddbdf
ABCDABCDEFACDDBDF
abcdabcdefacddbdf
Abcdabcdefacddbdf
 

3.8.Python格式系列

lstrip(去除左邊空格),rstrip(去除右邊空格)

strip (去除兩邊空格)美化輸出系列:ljust,rjust,center

ljust,rjust,center這些就不說了,python常常在linux終端中輸出,因此這幾個用的比較多

In [18]:
# 格式系列:lstrip(去除左邊空格),rstrip(去除右邊空格),strip(去除兩邊空格)美化輸出系列:ljust,rjust,center
strip_str=" I Have a Dream "
print(strip_str.strip()+"|")#我加 | 是爲了看清後面空格,沒有別的用處
print(strip_str.lstrip()+"|")
print(strip_str.rstrip()+"|")

#這個就是格式化輸出,就不講了
print(test_str.ljust(50))
print(test_str.rjust(50))
print(test_str.center(50))
 
I Have a Dream|
I Have a Dream |
 I Have a Dream|
ABCDabcdefacddbdf                                 
                                 ABCDabcdefacddbdf
                ABCDabcdefacddbdf                 
 

3.9.Python驗證系列

isalpha(是不是純字母),isalnum(是不是數字|字母)

isdigit(是不是純數字),isspace(是不是純空格)

注意~ test_str5=" \t \n " # isspace() ==>true

In [19]:
# 驗證系列:isalpha(是不是純字母),isalnum(是不是數字|字母),isdigit(是不是純數字),isspace(是不是純空格)
# 注意哦~ test_str5=" \t \n " #isspace() ==>true

test_str2="Abcd123"
test_str3="123456"
test_str4="  \t"     #isspace() ==>true
test_str5="  \t\n " #isspace() ==>true
In [20]:
test_str.isalpha() #是不是純字母
Out[20]:
True
In [21]:
test_str.isalnum() #是不是數字|字母
Out[21]:
True
In [22]:
test_str.isdigit() #是不是純數字
Out[22]:
False
In [23]:
test_str.isspace() #是不是純空格
Out[23]:
False
In [24]:
test_str2.isalnum() #是不是數字和字母組成
Out[24]:
True
In [25]:
test_str2.isdigit() #是不是純數字
Out[25]:
False
In [26]:
test_str3.isdigit() #是不是純數字
Out[26]:
True
In [27]:
test_str5.isspace() #是不是純空格
Out[27]:
True
In [28]:
test_str4.isspace() #是不是純空格
Out[28]:
True
 

Python補充

像這些方法練習用ipython3就行了(sudo apt-get install ipython3

code的話須要一個個的print,比較麻煩(我這邊由於須要寫文章,因此只能一個個code)

圖片

 

4.CSharp字符串方法系列

4.1.查找

index0f就至關於python裏面的find

LastIndexOf ==> rfind

In [29]:
%%script csharp
var test_str = "ABCDabcdefacddbdf";

//# # 查找:find,rfind,index,rindex
//# # xxx.find(str, start, end)
//# print(test_str.find("cd"))#從左往右
Console.WriteLine(test_str.IndexOf('a'));//4
Console.WriteLine(test_str.IndexOf("cd"));//6

//# print(test_str.rfind("cd"))#從右往左
Console.WriteLine(test_str.LastIndexOf("cd"));//11

//# print(test_str.find("dnt"))#find和rfind找不到就返回-1
Console.WriteLine(test_str.IndexOf("dnt"));//-1
 
4
6
11
-1
 

4.2.計數

這個真用基礎來解決的話,兩種方法:

第一種本身變形一下:(原字符串長度 - 替換後的長度) / 字符串長度

//# # 計數:count
//# # xxx.count(str, start, end)
// print(test_str.count("d"))#4
// print(test_str.count("cd"))#2
// 第一反應,字典、正則、linq,後來想怎麼用基礎知識解決,因而有了這個~(原字符串長度-替換後的長度)/字符串長度

Console.WriteLine(test_str.Length - test_str.Replace("d", "").Length);//統計單個字符就簡單了
Console.WriteLine((test_str.Length - test_str.Replace("cd", "").Length) / "cd".Length);
Console.WriteLine(test_str);//不用擔憂原字符串改變(python和C#都是有字符串不可變性的)

字符串統計另外一種方法(就用index)

int count = 0;
int index = input.IndexOf("abc");

while (index != -1)
{
    count++;
    index = input.IndexOf("abc", index + 3);//index指向abc的後一位
}
 

4.3.替換

替換指定次數的功能有點業餘,就不說了,你能夠自行思考哦~

In [32]:
%%script csharp
var test_str = "ABCDabcdefacddbdf";
Console.WriteLine(test_str.Replace("b", "B"));
 
ABCDaBcdefacddBdf
 

4.4.分割

split裏面不少重載方法,能夠本身去查看下

eg:Split("\n",StringSplitOptions.RemoveEmptyEntries)

再說一下這個:test_str.Split('a'); //返回數組

若是要和Python同樣返回列表==》test_str.Split('a').ToList(); 【須要引用linq的命名空間哦】

var test_array = test_str.Split('a');//返回數組(若是要返回列表==》test_str.Split('a').ToList();)
var test_input = "hi my name is dnt";
//# print(test_input.split(" ")) #返回列表格式(後面會說)['hi', 'my', 'name', 'is', 'dnt']
test_input.Split(" ");
//# 按行分割,返回類型爲List
var test_line_str = "abc\nbca\ncab\n";
//# print(test_line_str.splitlines())#['abc', 'bca', 'cab']
test_line_str.Split("\n", StringSplitOptions.RemoveEmptyEntries);
 

4.5.鏈接

string.Join(分隔符,數組)

Console.WriteLine(string.Join("-", test_array));//test_array是數組 ABCD-bcdef-cddbdf

4.6.頭尾判斷

StartsWith(以。。。開頭),EndsWith(以。。。結尾)

In [35]:
%%script csharp
var start_end_str = "http://www.baidu.net";
//# print(start_end_str.startswith("https://") or start_end_str.startswith("http://"))
System.Console.WriteLine(start_end_str.StartsWith("https://") || start_end_str.StartsWith("http://"));
//# print(start_end_str.endswith(".com"))
System.Console.WriteLine(start_end_str.EndsWith(".com"));
 
True
False
 

4.7.大小寫系

//# print(test_str.upper())#ABCDABCDEFACDDBDF
Console.WriteLine(test_str.ToUpper());
//# print(test_str.lower())#abcdabcdefacddbdf
Console.WriteLine(test_str.ToLower());

4.8.格式化系

Tirm很強大,除了去空格還能夠去除你想去除的任意字符

net裏面string.Format各類格式化輸出,能夠參考,這邊就不講了

In [36]:
%%script csharp
var strip_str = " I Have a Dream ";
//# print(strip_str.strip()+"|")#我加 | 是爲了看清後面空格,沒有別的用處
Console.WriteLine(strip_str.Trim() + "|");
//# print(strip_str.lstrip()+"|")
Console.WriteLine(strip_str.TrimStart() + "|");
//# print(strip_str.rstrip()+"|")
Console.WriteLine(strip_str.TrimEnd() + "|");
 
I Have a Dream|
I Have a Dream |
 I Have a Dream|
 

4.9.驗證系列

string.IsNullOrEmptystring.IsNullOrWhiteSpace 是系統自帶的

In [37]:
%%script csharp
var test_str4 = "  \t";
var test_str5 = "  \t \n "; //#isspace() ==>true
// string.IsNullOrEmpty 和 string.IsNullOrWhiteSpace 是系統自帶的,其餘的你須要本身封裝一個擴展類
Console.WriteLine(string.IsNullOrEmpty(test_str4)); //false
Console.WriteLine(string.IsNullOrWhiteSpace(test_str4));//true
Console.WriteLine(string.IsNullOrEmpty(test_str5));//false
Console.WriteLine(string.IsNullOrWhiteSpace(test_str5));//true
 
False
True
False
True
 

其餘的你須要本身封裝一個擴展類(eg:簡單封裝

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

public static partial class ValidationHelper
{
    #region 經常使用驗證

    #region 集合系列
    /// <summary>
    /// 判斷集合是否有數據
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <returns></returns>
    public static bool ExistsData<T>(this IEnumerable<T> list)
    {
        bool b = false;
        if (list != null && list.Count() > 0)
        {
            b = true;
        }
        return b;
    } 
    #endregion

    #region Null判斷系列
    /// <summary>
    /// 判斷是否爲空或Null
    /// </summary>
    /// <param name="objStr"></param>
    /// <returns></returns>
    public static bool IsNullOrWhiteSpace(this string objStr)
    {
        if (string.IsNullOrWhiteSpace(objStr))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// 判斷類型是否爲可空類型
    /// </summary>
    /// <param name="theType"></param>
    /// <returns></returns>
    public static bool IsNullableType(Type theType)
    {
        return (theType.IsGenericType && theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
    }
    #endregion

    #region 數字字符串檢查
    /// <summary>
    /// 是否數字字符串(包括小數)
    /// </summary>
    /// <param name="objStr">輸入字符串</param>
    /// <returns></returns>
    public static bool IsNumber(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, @"^\d+(\.\d+)?$");
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 是不是浮點數
    /// </summary>
    /// <param name="objStr">輸入字符串</param>
    /// <returns></returns>
    public static bool IsDecimal(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, @"^(-?\d+)(\.\d+)?$");
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #endregion

    #region 業務經常使用

    #region 中文檢測
    /// <summary>
    /// 檢測是否有中文字符
    /// </summary>
    /// <param name="objStr"></param>
    /// <returns></returns>
    public static bool IsZhCN(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, "[\u4e00-\u9fa5]");
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #region 郵箱驗證
    /// <summary>
    /// 判斷郵箱地址是否正確
    /// </summary>
    /// <param name="objStr"></param>
    /// <returns></returns>
    public static bool IsEmail(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #region IP系列驗證
    /// <summary>
    /// 是否爲ip
    /// </summary>
    /// <param name="objStr"></param>
    /// <returns></returns>
    public static bool IsIP(this string objStr)
    {
        return Regex.IsMatch(objStr, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
    }

    /// <summary>  
    /// 判斷輸入的字符串是不是表示一個IP地址  
    /// </summary>  
    /// <param name="objStr">被比較的字符串</param>  
    /// <returns>是IP地址則爲True</returns>  
    public static bool IsIPv4(this string objStr)
    {
        string[] IPs = objStr.Split('.');
        for (int i = 0; i < IPs.Length; i++)
        {
            if (!Regex.IsMatch(IPs[i], @"^\d+$"))
            {
                return false;
            }
            if (Convert.ToUInt16(IPs[i]) > 255)
            {
                return false;
            }
        }
        return true;
    }

    /// <summary>
    /// 判斷輸入的字符串是不是合法的IPV6 地址  
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static bool IsIPV6(string input)
    {
        string temp = input;
        string[] strs = temp.Split(':');
        if (strs.Length > 8)
        {
            return false;
        }
        int count = input.GetStrCount("::");
        if (count > 1)
        {
            return false;
        }
        else if (count == 0)
        {
            return Regex.IsMatch(input, @"^([\da-f]{1,4}:){7}[\da-f]{1,4}$");
        }
        else
        {
            return Regex.IsMatch(input, @"^([\da-f]{1,4}:){0,5}::([\da-f]{1,4}:){0,5}[\da-f]{1,4}$");
        }
    }
    #endregion

    #region 網址系列驗證
    /// <summary>
    /// 驗證網址是否正確(http:或者https:)【後期添加 // 的狀況】
    /// </summary>
    /// <param name="objStr">地址</param>
    /// <returns></returns>
    public static bool IsWebUrl(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, @"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?|https://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 判斷輸入的字符串是不是一個超連接  
    /// </summary>
    /// <param name="objStr"></param>
    /// <returns></returns>
    public static bool IsURL(this string objStr)
    {
        string pattern = @"^[a-zA-Z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$";
        return Regex.IsMatch(objStr, pattern);
    }
    #endregion

    #region 郵政編碼驗證
    /// <summary>
    /// 驗證郵政編碼是否正確
    /// </summary>
    /// <param name="objStr">輸入字符串</param>
    /// <returns></returns>
    public static bool IsZipCode(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, @"\d{6}");
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #region 電話+手機驗證
    /// <summary>
    /// 驗證手機號是否正確
    /// </summary>
    /// <param name="objStr">手機號</param>
    /// <returns></returns>
    public static bool IsMobile(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, @"^13[0-9]{9}|15[012356789][0-9]{8}|18[0123456789][0-9]{8}|147[0-9]{8}$");
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 匹配3位或4位區號的電話號碼,其中區號能夠用小括號括起來,也能夠不用,區號與本地號間能夠用連字號或空格間隔,也能夠沒有間隔   
    /// </summary>
    /// <param name="objStr"></param>
    /// <returns></returns>
    public static bool IsPhone(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, "^\\(0\\d{2}\\)[- ]?\\d{8}$|^0\\d{2}[- ]?\\d{8}$|^\\(0\\d{3}\\)[- ]?\\d{7}$|^0\\d{3}[- ]?\\d{7}$");
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #region 字母或數字驗證
    /// <summary>
    /// 是否只是字母或數字
    /// </summary>
    /// <param name="objStr"></param>
    /// <returns></returns>
    public static bool IsAbcOr123(this string objStr)
    {
        try
        {
            return Regex.IsMatch(objStr, @"^[0-9a-zA-Z\$]+$");
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #endregion
}
相關文章
相關標籤/搜索