C++ 正則表達式


//1.當函數返回string時候的注意點:
string Fun()
{
	return string("szn");
}

const char* pStr = Fun().c_str();
//如上代碼,pStr = "" 而非 "szn",原因:返回的string變量被析構了


//2.正則表達式組件:
regex:用於表示一個正則表達式
regex_match:將一個字符序列與一個正則表達式匹配
regex_search:尋找第一個與正則表達式匹配的子序列
regex_replace:使用給定格式替換一個正則表達式
sregex_iterator:迭代器適配器,調用regex_search來遍歷一個string中所有匹配的字串
smatch:容器類,保存在string中搜索的結果
ssub_match:string中匹配的子表達式的結果

regex文件中的一些定義:
typedef basic_regex<char> regex;
typedef basic_regex<wchar_t> wregex;
typedef match_results<const char *> cmatch;
typedef match_results<const wchar_t *> wcmatch;
typedef match_results<string::const_iterator> smatch;
typedef match_results<wstring::const_iterator> wsmatch;

regex_search, regex_match的參數(返回值均為bool類型):
seq, m, r, mft
seq, r, mft
seq:字符序列
m:與seq兼容的match對象
r:一個正則表達式
mtf:可選值,用來保存匹配結果的相關細節

輸入類型與正則表達式庫對應關系:
string			regex, smatch, ssub_match, sregex_iterator
const char*		regex, cmatch, csub_match, cregex_iterator
wstring			wregex, wsmatch, wssub_match, wsregex_iterator
const wchar_t*	wregex, wcmatch, wcsub_match, wcregex_iterator

regex(和 wregex)選項:
regex r(re, f):f為可選參數,默認為 regex::ECMAScript,此標志控制regex對象的處理過程
	f:
	regex::icase		忽略大小寫
	regex::nosubs		不保存匹配的子表達式
	regex::optimize		執行速度優於構造速度
	regex::ECMAScript	
	regex::basic
	regex::extended
	regex::awk
	regex::grep
	regex::egrep
=:賦值操作
	regex re;
	re = "[123]";
r.assign(re, f):功能等同於賦值操作
r.mark_count():r中表達式數目
r.flags():返回r的標志集


//3.regex_search使用示例:
regex re("[[:alpha:]]*[^c]ei[[:alpha:]]*");
cmatch cm;
if (regex_search("receipt freind theif recive", cm, re))
{
	const char* pStrC = cm.str().c_str();	//pStrC = ""
	string str = cm.str();					//str = "freind"
}

regex re("[a-z]+", regex::icase);
smatch sm;
string strContent("12 3456ABCabc7 89");
if (regex_search(strContent, sm, re))
{
	string str = sm.str();					//str = "ABCabc"
}
ssub_match subMatch = sm[0];
string str = subMatch;						//str = "ABCabc"


//4.
A:一個正則表達式的語法是否正確是在運行時候進行解析的
B:若編寫的正則表達式有誤,則運行時,標准庫會拋出一個regex_error的異常
C:正則表達式的編譯可能會是一個非常慢的操作,所以要避免創建很多沒必要的regex變量
try
{
	regex re("[");
}
catch (std::regex_error e)					//e = {_Err=error_brack }
{
	printf("");								//運行至此
}

enum error_type
{	// identify error
	error_collate,
	error_ctype,
	error_escape,
	error_backref,
	error_brack,
	error_paren,
	error_brace,
	error_badbrace,
	error_range,
	error_space,
	error_badrepeat,
	error_complexity,
	error_stack,
	error_parse,
	error_syntax
};

//5.sregex_iterator
A:sregex_iterator it(b, e, r); 一個 sregex_iterator 遍歷迭代器表示string,調用 regex_search 將 it 定位到輸入中第一個匹配的位置
B:sregex_iterator end; sregex_iterator 的尾后迭代器
C:*it it-> 根據最后一個調用 regex_search 的結果,返回一個 smatch 對象的指針或引用
D:++it it++ 從輸入序列當前位置開始調用 regex_search

使用示例
string str = "abc 123 sdfd4567sdf 456 sdf";
regex re(" ([0-9]+) ");
smatch sm;
vector<string> vecStr[2];

for (sregex_iterator it(str.begin(), str.end(), re), ItEnd; it != ItEnd; ++it)
{
	vecStr[0].emplace_back(it->str()); 
	vecStr[1].emplace_back(it->str(1));
}
//vecStr[0] = [2](" 123 "," 456 ")
//vecStr[1] = [2]("123","456")


//6.
A:正則語法通常用括號表示子表達式


//7.regex_replace使用的簡單示例
regex re("[0-9]+");
string str("abc123efg456");
string str0 = regex_replace(str, re, string("Test"));												//str0 = "abcTestefgTest"
string str1 = regex_replace(str, re, string("Test"), std::regex_constants::format_first_only);		//str1 = "abcTestefg456"

string str("123abc45_abc_67");
regex re("([0-9]+)([a-z]+)([0-9]+)");
std::smatch sm;
if (regex_search(str, sm, re))
{
	string str0 = sm.str(0);		//str0 = "123abc45"
	string str1 = sm.str(1);		//str1 = "123"	
	string str2 = sm.str(2);		//str2 = "abc"
	string str3 = sm.str(3);		//str3 = "45"
}
string strRe0 = std::regex_replace(str, re, string("szn"));		//strRe0 = "szn_abc_67"
string strRe1 = std::regex_replace(str, re, string("$1szn$3"));	//strRe1 = "123szn45_abc_67"

match_default = 0x0000,		//默認
match_not_bol = 0x0001,		//不將首字符作為行首處理
match_not_eol = 0x0002,		//不將尾字符作為行尾處理
match_not_bow = 0x0004,		//不將首字符作為單詞首處理
match_not_eow = 0x0008,		//不將尾字符作為單詞尾處理
match_any = 0x0010,			//若存在多個匹配,則返回任意一個匹配
match_not_null = 0x0020,	//不匹配任何空序列
match_continuous = 0x0040,	//匹配必須從輸入的首字符開始
match_prev_avail = 0x0100,	//輸入序列包含第一個匹配之前的內容
format_default = 0x0000,	//用ECMAScript規則替換字符串
format_sed = 0x0400,		//用POXIS sed規則替換字符串
format_no_copy = 0x0800,	//不輸出輸入部分中未匹配的部分
format_first_only = 0x1000,	//只替換子表達式第一次出現的位置


//8.regex_match使用示例
regex re0("[0-9]+");
regex re1("[0-9a-z]+");
string str("abc123");
bool nRe0 = regex_match(str, re0);	//nRe0 = false
bool nRe1 = regex_match(str, re1);	//nRe1 = true

regex_match 必須匹配被分析串的全部,若不匹配返回 false ,否則返回 true

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM