正則表達式的使用

什麼是正則表達式

正則表達式是用字符序列來描述複雜查詢條件的方式。

匹配所有的數字

^[0-9]+$

表達式說明:
* ^ - 表示一行的開始
* [0-9] - 匹配介於0-9中間的任何數字;也可以用\d來代替
* + - 匹配前面表達式的一個或者多個實例
* $ - 表示一行的結束

不同語言實現正則表達式

C#語言下實現

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;

namespace RegexExample
{
    class FileRegexExample
    {
        static void Main()
        {
            string text = File.ReadAllText(@"./test.txt", Encoding.UTF8);
            Regex regex = new Regex("^[0-9]+$", RegexOptions.Multiline);
            MatchCollection mc = regex.Matches(text);
            var matches = mc.OfType<Match>().Select(m => m.Value).ToArray();
            Console.WriteLine(string.Join(" ", matches));
        }
    }
}

Python語言下實現

import re

with open('test.txt', 'r') as line:
  testString = line.read()
  regex = re.compile(r'^([0-9]+)$', re.MULTILINE)
  result = regex.findall(testString)
  print(result)

C++語言下實現

#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <regex>
using namespace std;

int main () {
  ifstream t("test.txt");
  stringstream buffer;
  buffer << t.rdbuf();
  string testString = buffer.str();

  regex numberLineRegex("(^|\n)([0-9]+)($|\n)");
  sregex_iterator it(testString.begin(), testString.end(), numberLineRegex);
  sregex_iterator it_end;

  while(it != it_end) {
    cout << it -> str();
    ++it;
  }
}

匹配年份

\b(19|20)\d{2}\b

表達式說明:
* \b - 單詞邊界
* (19|20) - 匹配19或者20數字
* \d{2} - 兩位數字,與[0-9]{2}相似
* \b - 單詞邊界

匹配時間

\b([01]?[0-9]|2[0-3]):([0-5]\d)\b
  • \b - 單詞邊界
  • [01] - 0 或者 1
  • ? - 表示前面的條件或者模式是可選的
  • [0-9] - 匹配0-9的所有數字
  • | - 或者
  • 2[0-3] - 20、21、22、23
  • : - 匹配:字符
  • [0-5] - 匹配0-5之間的數字
  • \d - 匹配0-9之間的所有數字
  • \b - 單詞邊界

匹配日期

\b(0?[1-9]|[12]\d|3[01])([\/\-])(0?[1-9]|1[012])\2(\d{4})

DAY/MONTH/YEAR表達式說明:
* (0?[1-9]|[12]\d|3[01]) - 匹配1-31之間的任何數字,首字符可以是0
* ([\/\-]) - 匹配所有的分隔符/或者-
* (0?[1-9]|1[012]) - 匹配所有的1-12之間的字符
* \2 - 匹配分組
* \d{4} - 匹配任何四位數字

驗證郵箱

^[^@\s]+@[^@\s]+\.\w{2,6}$

表達式說明:
* ^ - 輸入開始
* [^@\s] - 匹配除了所有的字符除了@和空格\s
* + - 1+次
* @ - 匹配@標誌
* [^@\s]+ - 匹配除了所有的字符除了@和空格\s; 1+次
* \. - 匹配’.’字符
* \w{2,6} - 匹配任何字符,2-6次
* $ - 輸入結束

匹配URL

(https?:\/\/)(www\.)?(?<domain>[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6})(?<path>\/[-a-zA-Z0-9@:%_\/+.~#?&=]*)?

表達式說明:
* (https?:\/\/) - 匹配http或者https
* (www\.)? - 匹配’www’前綴(可選)
* (?<domain>[-a-zA-Z0-9@:%._\+~#=]{2,256} - 匹配有效的域名
* \.[a-z]{2,6}) - 匹配域名後綴
* (?<path>\/[-a-zA-Z0-9@:%_\/+.~#?&=]*)? - 匹配URL路徑(/posts), 查詢字符條件(?limit=1), and/or 文件後綴(.html), 全可選.

注:參考內容

發佈了53 篇原創文章 · 獲贊 29 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章