正则表达式的使用

什么是正则表达式

正则表达式是用字符序列来描述复杂查询条件的方式。

匹配所有的数字

^[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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章