C++编程语言:标准库:第37章——正则表达式(Bjarne Stroustrup)

TL494充电器原理与维修 (转) TL494充电器原理与维修 电动自行车充电器多采用开关 电源,型号虽多,但电路结构大同小异,主要区别在于所选的脉宽调制(PWM)芯片不同如(UC3845、UC3842、SG3524、TL494)。现以佳腾牌 充电器为例,介绍其原理和故障检修方法。 一、电路原理 根据实物测绘的佳腾牌充电器电路原理如图1所示。整机可分为PWM产生和推动电路、功 率开关变换电路、... 阅读详情

第 37章  正则表达式(Regular Expressions)

目录

37.1  正则表达式(规范表达式)(Regular Expressions)

37.1.1  正则表达式相关符号(Regular Express Notation)

37.2  regex

37.2.1  匹配结果(Match Results)

37.2.2  格式化(Formatting)

37.3 正则表达式函数

37.3.1  regex_match()

37.3.2  regex_search()

37.3.3  regex_replace()

37.4 正则表达式迭代器

37.4.1  regex_iterator

37.4.2  regex_token_iterator

37.5  regex_traits

37.6  建议


37.1  正则表达式(规范表达式)(Regular Expressions)

         在 <regex> 中,标准库提供了正则表达式:

•  regex_match():将正则表达式与已知长度的字符串进行匹配。

•  regex_search():在任意长度的数据流中搜索与正则表达式匹配的字符串。

•  regex_replace():在任意长度的数据流中搜索与正则表达式匹配的字符串并进行替换。

•  regex_iterator:迭代匹配项和子匹配项。

•  regex_token_iterator:迭代不匹配项。

regex_search() 的结果是匹配的集合,通常表示为 smatch:

void use()

{

ifstream in("file.txt"); // input file

if (!in) cerr << "no file\n";

regex pat {R"(\w{2}\s∗\d{5}(−\d{4})?)"}; // U.S. postal code pattern

int lineno = 0;

for (string line; getline(in,line);) {

++lineno;

smatch matches; // matched strings go here

if (regex_search(line , matches, pat)) {

cout << lineno << ": " << matches[0] << '\n'; // the complete match

if (1<matches.siz e() && matches[1].matched)

cout << "\t: " << matches[1] << '\n';// submatch

}

}

}

此函数读取一个文件,查找美国邮政编码,例如 TX77845 和 DC 20500-0001。smatch 类型是正则表达式结果的容器。其中,matches[0] 表示整个模式,matches[1] 表示可选的四位子模式。我使用了原始字符串(§7.3.2.1),它特别适合正则表达式,因为正则表达式通常包含大量反斜杠。如果我使用传统的字符串,则模式定义如下:

regex pat {"\\w{2}\\s∗\\d{5}(−\\d{4})?"}; // U.S. postal code pattern

         正则表达式的语法和语义经过精心设计,以便能够将其编译成状态机,从而高效执行 [Cox,2007]。regex 类型在运行时执行此编译。

37.1.1  正则表达式相关符号(Regular Express Notation)

         regex 库可以识别正则表达式的多种表示法变体(见第 37.2 节)。这里,我首先介绍默认使用的表示法,它是 ECMAScript(通常称为 JavaScript)中使用的 ECMA 标准的一种变体。

       正则表达式的语法基于具有特殊意义的字符:

正则表达式特殊字符

.

任意单字符(通配符(wildcard))

[

字符类开始

]

字符类结束

{

开始计数

}

结束计数

(

分组开始

)

分组结束

\

下一个字符具有特别的意义(转义字符)

*

0个或以上

+

1个或以上

?

可选(0个或1个)

|

替代对象(或运算)

ˆ

匹配行之开始;取反操作

$

匹配行之结束

例如,我们可以指定一行,以零个或多个 A 开头,后跟一个或多个 B,然后是一个可选的 C,如下所示:

ˆA∗B+C?$

匹配的例子:

AAAAAAAAAAAABBBBBBBBBC

BC

B

不匹配的例子:

AAAAA //无 B

AAAABC //开头出现空白

AABBCC //太多C

如果模式的一部分被括在括号中,则该部分被视为子模式(可以从 smatch 中单独提取)。

    通过添加后缀,模式可以是可选的,也可以是重复的(默认是1次):

重复

{ n }

恰好 n 次

{ n, }

n或以上次数

{n,m}

至少n次且至多m次

∗

0或以上次数,即 { 0, }

+

1或以上次数,即  { 1, }

?

可选(0次或1次),即 (0,1)

例如:

A{3}B{2,4}C∗

匹配的例子:

AAABBC

AAABBB

不匹配的例子:

AABBC //太少A

AAABC //太少B

AAABBBBBCCC // 太多B

在任何重复符号后添加后缀 ? 会使模式匹配器变成“惰性(lazy)”或“非贪婪(non-greedy)”。也就是说,在查找模式时,它会查找最短匹配,而不是最长匹配。在默认情况下,模式匹配器始终查找最长匹配(类似于 C++ 的 Max Munch 规则;§10.3)。考虑:

ababab

模式 (ab)∗ 匹配所有 ababab。然而,(ab)∗? 只匹配第一个 ab。

    最常见的字符分类有名称:

字符分类

alnum

任意字母数字字符

alpha

任意字母字符

blank

任意非行分隔符的空白字符

cntrl

任意控制字符

d

任意十进制数

digit

任意十进制数

graph

任意图形字符

lower

任意小写字符

print

任意可打印字符

punct

任何标点符号字符

s

任意空白字符

space

任意空白字符

upper

任意大写字符

w

任意词字符(字母数字字符加下划线)

xdigit

何意16进制数字符

支持几种字条类缩写:

缩写的字符类

\d

一个十进制数

[[:digit:]]

\s

一个空白(空白,跳格,等等)

[[:space:]]

\w

一个字母(a-z)或数字(0-9)或下划线(_)

[_[:alnum:]]

\D

非  \d

[ˆ[:digit:]]

\S

非  \s

[ˆ[:space:]]

\W

非  \w

[ˆ_[:alnum:]]

此外,支持正则表达式的语言通常提供:

非标准但(常用的)缩写字符类

\l

一个小写字符

[[:lower:]]

\u

一个大写字符

[[:upper:]]

\L

非 \l

[ˆ[:lower:]]

\U

非  \u

[ˆ[:upper:]]

为了实现完全可移植性,请使用字符类名称而不是这些缩写。

    例如,考虑编写一个描述 C++ 标识符的模式:一个下划线或字母,后跟一个可能为空的字母、数字或下划线序列。为了说明其中的微妙之处,我列举了一些错误的尝试:

[:alpha:][:alnum:]∗ // 错: 来自集合“:alph”的字符,后跟...

[[:alpha:]][[:alnum:]]∗ // 错: 不接受下划线('_' 不是字母)

([[:alpha:]]|_)[[:alnum:]]∗ // 错: 下划线也不是 alnum 的一部分

([[:alpha:]]|_)([[:alnum:]]|_)∗ // 可, 但笨拙

[[:alpha:]_][[:alnum:]_]∗ // 可: 在字符类中包含下划线

[_[:alpha:]][_[:alnum:]]∗ // 也可

[_[:alpha:]]\w∗ // \w 等价于 [_[:alnum:]]

最后,这里有一个函数,它使用 regex_match() 的最简单版本(§37.3.1)来测试一个字符串是否是一个标识符:

bool is_identifier(const string& s)

{

regex pat {"[_[:alpha:]]\\w∗"};

return regex_match(s,pat);

}

注意,为了在普通字符串字面量(literal)中包含反斜杠,需要使用两个反斜杠。通常,反斜杠也可以表示特殊字符:

特殊字符(§iso.2.14.3, §6.2.3.2)

\n

换行

\t

跳格(制表符)

\\

一个反斜杠

\xhh

使用两个十六进制数字表示的 Unicode 字符

\uhhhh

使用四个十六进制数字表示的 Unicode 字符

为了增加混淆的机会,提供了反斜杠的另外两种逻辑上不同的用法:

特殊字符(§iso.28.5.2, §37.2.2)

\b

一个词的第一个或最后一个字符

\B

非 \b

\i

按这种模式第 i 个sub_match

使用原始字符串字面量(raw string literals)可以缓解许多特殊字符的问题。例如:

bool is_identifier(const string& s)

{

regex pat {R"([_[:alpha:]]\w∗)"};

return regex_match(s,pat);

}

以下是一些模式示例:

Ax∗ // A, Ax, Axxxx

Ax+ //Ax, Axxx Not A

\d−?\d //1-2, 12 Not 1--2

\w{2}−\d{4,5} // Ab-1234, XX-54321, 22-5432 Digits are in \w

(\d∗:)?(\d+) // 12:3, 1:23, 123, :123 Not 123:

(bs|BS) // bs, BS Not bS

[aeiouy] // a, o, u An English vowel, not x

[ˆaeiouy] // x, k Not an English vowel, not e

[aˆeiouy] // a, ˆ, o, u An English vowel or ˆ

一个可能由 sub_match 表示的group(一种子模式)由括号分隔。如果需要括号,但又不用于定义子模式,请使用 (? 而不是普通的 ( 。例如:

(\s|:|,)∗(\d∗) //后接一个数的空白, 冒号, 和/或 逗号

假设我们对数前的字符(可能是分隔符)不感兴趣,我们可以写为:

(?\s|:|,)∗(\d∗) //后接一个数的空白, 冒号, 和/或 逗号

这将使正则表达式引擎不必存储第一个字符:(? 变体只有一个子模式。

正则表达式分组示例

\d∗\s\w+

无分组(子模式)

(\d∗)\s(\w+)

两个分组

(\d∗)(\s(\w+))+

两个分组(分组不嵌套)

(\s∗\w∗)+

一个组,但包含一个或多个子模式;

只有最后一个子模式会保存为 sub_match

<(.∗?)>(.∗?)</\1>

三个分组;\1 表示“与第 1 组相同”

    最后一个模式对于解析 XML 非常有用。它可以查找标签/标签结束标记。请注意,我使用了非贪婪匹配(惰性匹配),.∗? 作为标签和结束标签之间的子模式。如果我使用普通的 .∗,则此输入会导致问题:

Always look for the <b>bright</b> side of <b>life</b>.

对第一个子模式进行贪婪匹配会将第一个 < 与最后一个 > 匹配。对第二个子模式进行贪婪匹配会将第一个 <b> 与最后一个 </b> 匹配。这两种行为都是正确的,但不太可能是程序员想要的。

    可以使用选项(§37.2)改变正则表达式符号的细节。例如,如果使用 regex_constants::grep,则 a?x:y 是一个由五个普通字符组成的序列,因为 ? 在 grep 中不表示“可选”。

    有关正则表达式的更详尽介绍,请参阅 [Friedl,1997]。

37.2  regex

    正则表达式是由字符序列(例如string)构成的匹配引擎(通常是状态机):

template<class C, class traits = regex_traits<C>>

class basic_regex {

public:

using value_type = C;

using traits_type = traits;

using string_type = typename traits::string_type;

using flag_type = regex_constants::syntax_option_type;

using locale_type = typename traits::locale_type;

˜basic_regex(); // not virtual; basic_regex is not meant to be used as a base class

// ...

};

regex_traits 见 §37.5 。

与string一样,regex是使用char版本的别名:

using regex = basic_regex<char>;

正则表达式模式的含义由 regex_constants 和 regex 中定义相同的 syntax_option_type 常量控制:

basic_regex<C,Tr> 成员(syntax_option_type, §iso.28.5.1)

icase

匹配时不区分大小写

nosubs

匹配结果中不存储任何子表达式匹配

optimize

优先考虑快速匹配而不是快速正则表达式对象构造

collate

形式为 [a−b] 的字符范围是局部敏感的

ECMAScript

正则表达式语法是 ECMAScript 在 ECMA-262 中使用的语法(略有修改;§iso.28.13)

basic

正则表达式语法是 POSIX 中基本正则表达式所使用的语法

extended

正则表达式语法是 POSIX 中的扩展正则表达式所使用的语法

awk

正则表达式语法是 POSIX awk 使用的语法

grep

正则表达式语法是 POSIX grep 使用的语法

egrep

正则表达式语法是 POSIX egrep 使用的语法

除非有充分的理由,否则请使用默认值。充分的理由包括大量现有的正则表达式都采用了非默认的表示法。

    regex对象可以由string或类似的字符序列构造:

basic_regex<C,Tr> 构造函数(§iso.28.8.2)

basic_regex r {};

默认构造函数:一个空模式;

标志设置为 regex_constants::ECMAScript

basic_regex r {x,flags};

x 可以是 basic_regex、string、C 风格字符串或一个带有 flags 定义的符号的 initializer_list<value_type>;explicit

basic_regex r {x};

basic_regex{x,reg ex_constants::ECMAScript}; explicit

basic_regex r {p,n,flags};

使用 flags 定义的符号,从 [p:p+n) 中的字符构造 r

basic_regex r {p,n};

basic_regex{p,n,reg ex_constants::ECMAScript}

basic_regex r {b,e ,flags}

使用 flags 定义的符号,根据 [b:e) 中的字符构造 r

basic_regex r {b,e};

basic_regex{b,e ,regex_constants::ECMAScript}

    regex的主要用途贯穿搜索、匹配和替换功能(§37.3),但正则表达式本身也有一些操作:

basic_regex<C,Tr> 操作(§iso.28.8)

r=x

复制赋值:x 可以是 basic_regex,C风格字符串,basic_string  ,或者initializer_list<value_type>

r=move(r2)

移动赋值

r=r.assign(r2)

复制或移动

r=r.assign(x,flags)

复制或移动;将 r 的标志设置为标志 x 可以是 basic_string、C 样式字符串或 initializer_list<value_type>

r=r.assign(x)

r=r.assign(x,reg ex_constants::ECMAScript)

r=r.assign(p,n,flags)

将 r 的模式设置为 [p:p+n),并将 r 的标志设置为 flags

r=r.assign(b,e ,flags)

将r 的模式设置为 [b:e),将 r 的标志设置为 flags

r=r.assign(b,e)

r=r.assign(b,e ,regex_constants::ECMAScript)

n=r.mark_count()

n 是 r 中标记子表达式的数量

x=r.flags()

x 是 r 的标志

loc2=r.imbue(loc)

r 获取语言环境 loc;loc2 是 r 之前的语言环境

loc=r.g etloc()

loc 是 r 的语言环境

r.swap(r2)

交换 r 和 r2 的值

你可以通过调用 getloc() 来确定locale或regex,并通过 flags() 了解所使用的标志,但遗憾的是,没有(标准)方法来读取其模式。如果您需要输出模式,请保留用于初始化的字符串的副本。例如:

regex pat1 {R"(\w+\d∗)"}; // 无法输出 pat1 中的模式

string s {R"(\w+\d∗)"};

regex pat2 {s};

cout << s << '\n'; // pat2 中的模式

37.2.1  匹配结果(Match Results)

    正则表达式匹配的结果收集于 match_results 对象中,该对象包含一个或多个 sub_match 对象:

template<class Bi>

class sub_match : public pair<Bi,Bi> {

public:

using value_type = typename iterator_traits<Bi>::value_type;

using difference_type = typename iterator_traits<Bi>::difference_type;

using iterator = Bi;

using string_type = basic_string<value_type>;

bool matched; // true if *this contains a match

// ...

};

Bi 必须是双向迭代器 (§33.1.2)。sub_match 可以看作是一对迭代器,指向被匹配的字符串。

sub_match<Bi> 操作

sub_match sm {};

默认构造函数:一个空序列;constexpr

n=sm.length()

n 是匹配的字符数

s=sm

将 sub_match 隐式转换为 basic_string;s 是包含匹配字符的 basic_string

s=sm.str()

s 是包含匹配字符的 basic_string

x=sm.compare(x)

字典顺序比较:sm.str().compare(x);

x 可以是 sub_match、basic_string 或 C 风格字符串

x==y

x 等于 y 吗?x 和 y 可以是 sub_match 或 basic_string

x!=y

!(x==y)

x<y

x 按字典顺序位于y 之前

x>y

y<x

x<=y

!(x>y)

x>=y

!(x<y)

sm.matched

如果 sm 包含匹配项,则为 true;否则为 false

例如:

regex pat ("<(.∗?)>(.∗?)</(.∗?)>");

string s = "Always look for the <b> bright </b> side of <b> death </b>";

if (regex_search(s1,m,p2))

if (m[1]==m[3]) cout << "match\n";

输出是 match 。

   一个 match_results 是一个 sub_match 的容器:

template<class Bi, class A = allocator<sub_match<Bi>>

class match_results {

public:

using value_type = sub_match<Bi>;

using const_reference = const value_type&;

using reference = const_reference;

using const_iterator = /* implementation-defined */;

using iterator = const_iterator;

using difference_type = typename iterator_traits<Bi>::difference_type;

using size_type = typename allocator_traits<A>::size_type;

using allocator_type = A;

using char_type = typename iterator_traits<Bi>::value_type;

using string_type = basic_string<char_type>;

˜match_results(); // not virtual

// ...

};

Bi 必须是双向迭代器(§33.1.2)。

    与 basic_string 和 basic_ostream 一样,为最常见的 match_results 提供了一些标准别名:

using cmatch = match_results<const char∗>; //C-style string

using wcmatch = match_results<const wchar_t∗>; //wide C-style string

using smatch = match_results<string::const_iterator>; // string

using wsmatch = match_results<wstring::const_iterator>; // wstring 

match_results 提供对其匹配字符串、其 sub_matches 以及匹配前后的字符的访问:

match_results 提供了一组常规操作:

regex<C,Tr> 匹配和子匹配(§iso.28.9, §iso.28.10)

match_results m {};

默认构造函数:使用 allocator_type{}

match_results m {a};

使用分配器a;explicit

match_results m {m2};

复制和移动构造函数

m2=m

复制赋值

m2=move(m)

移动赋值

m.˜match_results()

析构函数:释放所有资源

m.ready()

m 是否完全匹配?

n=m.size()

n−1 是 m 中子表达式的数量;如果没有匹配,则 n==0

n=m.max_size()

n 是 m 的最大可能的 sub_matches 数量

m.empty()

m.size()==0?

r=m[i]

r 是 m 中第 i 个 sub_match 的常量引用;

m[0] 表示完全匹配;

如果 i>= size(),则 m[i] 指向表示未匹配子表达式的 sub_match。

n=m.length(i)

n=m[i].length();m[i]的字符个数

n=m.length()

n=m.length(0)

pos=m.position(i)

pos=m[i].first;m[i]的第一个字符

pos=m.position()

pos=position(0)

s=m.str(i)

s=m[i].str();m[i]的字符串表示

s=m.str()

s=m.str(0)

sm=m.prefix()

sms 是一个 sub_match,表示输入字符串中匹配项之前未与 m 匹配的字符

sm=m.suffix()

sms 一个 sub_match,表示输入字符串中匹配结果之后未与 m 匹配的字符

p=m.begin()

p 指向 m 的第一个 sub_match

p=m.end()

p 指向 m 的最后一个子匹配项

p=m.cbegin()

p 指向 m 的第一个 sub_match(const 迭代器)

p=m.cend()

p 指向 m 的最后一个子匹配项之后的子匹配项(const 迭代器)

a=m.get_allocator()

a 是 m 的分配器

m.swap(m2)

交换 m 和 m2 的状态

m==m2

m 和 m2 的 sub_matches 值是否相等?

m!=m2

!(m==m2)

我们可以通过对 regex_match 添加下标来访问sub_match,例如 m[i]。如果下标 i 指向一个不存在的sub_match,则 m[i] 的结果表示该sub_match不匹配。例如:

void test()

{

regex pat ("(AAAA)(BBB)?");

string s = "AAAA";

smatch m;

regex_search(s,m,pat);

cout << boolalpha;

cout << m[0].matched << '\n'; // true: we found a match

cout << m[1].matched << '\n'; // true: there was a first sub_match

cout << m[2].matched << '\n'; // false: no second sub_match

cout << m[3].matched << '\n'; // false: there couldn’t be a third sub_match for pat

}

37.2.2  格式化(Formatting)

在 regex_replace() 中,格式化是使用 format() 函数完成的:

regex<C,Tr>  格式化(§iso.28.10.5)

格式由 match_flag_type 选项控制

out=m.format(out,b,e ,flags)

将 [b:e) 复制到 out;

用 m 中的子匹配替换格式字符

out=m.format(out,b,e)

out=m.format(out,b,e ,regex_constants::format_default)

out=m.format(out,fmt,flags)

out=m.format(out,begin(fmt),end(fmt),flags);

fmt 可以是 basic_string 或 C 风格字符串

out=m.format(out,fmt)

out=m.format(out,fmt,regex_constants::format_default)

s=m.format(fmt,flags)

将 s 构造为 fmt 的副本;

用 m 中的子匹配替换格式字符;

fmt 可以是 basic_string 或 C 风格字符串

s=m.format(fmt)

s=m.format(fmt,reg ex_constants::format_default)

格式可以包含格式字符:

格式替换符号

$&

匹配

$‘

前缀

$’

后缀

$i

第i个子匹配,例如$1

$ii

第ii个子匹配,例如$12

$$

不匹配,$字符

有关示例,请参阅§37.3.3。

format() 完成的格式化细节由一组选项(标志)控制:

regex<C,Tr>  格式化操作(regex_constants::match_flag_type; §iso.28.5.2)

format_default

使用 ECMAScript(ECMA-262)规则(§iso.28.13)

format_sed

使用 POSIX sed 符号

format_no_copy

仅复制匹配项

format_first_only

仅替换正则表达式的第一次出现

37.3 正则表达式函数

将正则表达式模式应用于数据的函数包括:regex_search()(用于在字符序列中搜索)、regex_match()(用于匹配固定长度的字符序列)以及regex_replace()(用于执行模式替换)。

    匹配的细节由一组选项(标志)控制:

regex<C,Tr> 匹配选项(regex_constants::match_flag_type; §iso.28.5.2)

match_not_bol

字符 ˆ 不被视为表示“行首”

match_not_eol

字符 $ 不被视为表示“行尾”

match_not_bow

\b 与子序列 [first,first) 不匹配

match_not_eow

\b 与子序列 [last,last) 不匹配

match_any

如果有多个匹配可能,则任何匹配都是可以接受的

match_not_null

不匹配空序列

match_continuous

仅匹配从first开始的子序列

match_prev_avail

−−first 是有效的迭代器位置

37.3.1  regex_match()

要求得与已知长度的整个序列(例如一行文本)匹配的模式,请使用 regex_match():

正则表达式匹配(§iso.28.11.2)

匹配由match_flag_type 选项控制(§37.3)

regex_match(b,e ,m,pat,flags)

输入 [b:e) 是否与正则表达式模式 pat 匹配?

将结果放入 match_results m;使用选项标志

regex_match(b,e ,m,pat)

regex_match(b,e ,m,pat,regex_constants::match_default)

regex_match(b,e ,pat,flags)

输入 [b:e) 是否与正则表达式模式 pat 匹配?使用选项标志

regex_match(b,e ,pat)

regex_match(b,e ,pat,regex_constants::match_default)

regex_match(x,m,pat,flags)

输入 x 是否与正则表达式模式 pat 匹配?

x 可以是 basic_string 或 C 语言风格的字符串;

将结果放入 match_results m 中;使用选项标志

regex_match(x,m,pat)

regex_match(x,m,pat,regex_constants::match_default)

regex_match(x,pat,flags)

输入 x 是否与正则表达式模式 pat 匹配?

x 可以是 basic_string 或 C 语言风格的字符串;请使用选项标志

regex_match(x,pat)

regex_match(x,pat,regex_constants::match_default)

举个例子,考虑一个用于验证表格格式的简单程序。如果表格格式符合预期,程序会向 cout 写入“一切正常”;如果不符合预期,程序会向 cerr 写入错误消息。表格由一系列行组成,每行包含四个以制表符分隔的字段,但第一行(标题行)可能只有三个字段。例如:

Class-----------Boys---------------Girls----------------Total

1a----------------12------------------- 15 -------------------27

1b ---------------16 -------------------14 -------------------30

Total ------------28 -------------------29 -------------------57

这些数字应该在水平和垂直方向上相加。

    程序读取标题行,然后对每一行进行求和,直到最后一行标记为“总计”:

int main()

{

ifstream in("table .txt"); // input file

if (!in) cerr << "no file\n";

string line; // input buffer

int lineno = 0;

regex header {R"(ˆ[\w ]+(\t[\w ]+)∗$)"}; //tab-separated words

regex row {R"(ˆ([\w ]+)(\t\d+)(\t\d+)(\t\d+)$)"}; // label followed by three tab-separated numbers

if (getline(in,line)) { // check and discard the header line

smatch matches;

if (!regex_match(line ,matches,header))

cerr << "no header\n";

}

int boys = 0; // running totals

int girls = 0;

while (getline(in,line)) {

++lineno;

smatch matches; //submatches go here

if (!regex_match(line ,matches,row))

cerr << "bad line: " << lineno << '\n';

int curr_boy = stoi(matches[2]); // for stoi() see §36.3.5

int curr_girl = stoi(matches[3]);

int curr_total = stoi(matches[4]);

if (curr_boy+curr_girl != curr_total) cerr << "bad row sum \n";

if (matches[1]=="Total") { // last line

if (curr_boy != boys) cerr << "boys do not add up\n";

if (curr_girl != girls) cerr << "girls do not add up\n";

cout << "all is well\n";

return 0;

}

boys += curr_boy;

girls += curr_girl;

}

cerr << "didn't find total line\n")

return 1;

}

37.3.2  regex_search()

       要在序列的一部分(例如文件)中查找模式,请使用 regex_search():

正则表达式搜索(§iso.28.11.3)

匹配由match_flag_type 选项控制(§37.3)

regex_search(b,e ,m,pat,flags)

输入 [b:e) 是否包含正则表达式模式 pat 的匹配项?将结果放入 match_results m;使用选项标志

regex_search (b,e ,m,pat)

regex_search(b,e ,m,regex_constants::match_default)

regex_search (b,e ,pat,flags)

输入 [b:e) 是否包含正则表达式模式 pat 的匹配项?请使用选项标志

regex_search (b,e ,pat)

regex_search(b,e ,pat,regex_constants::match_default)

regex_search (x,m,pat,flags)

输入 x 是否包含正则表达式模式 pat 的匹配项?

x 可以是 basic_string 或 C 语言风格的字符串;

将结果放入 match_results m 中;使用选项标志

regex_search (x,m,pat)

regex_search(x,m,pat,regex_constants::match_default)

regex_search (x,pat,flags)

输入 x 是否包含正则表达式模式 pat 的匹配项?

x 可以是 basic_string 或 C 语言风格的字符串;请使用选项标志

regex_search (x,pat)

regex_search(x,pat,regex_constants::match_default)

例如,我可以像这样查找我的名字的一些更常见的拼写错误:

regex pat {"[Ss]tro?u?v?p?stra?o?u?p?b?"};

smatch m;

for (string s; cin>>s; )

if (regex_search(s,m,pat))

if (m[0]!="stroustrup" && m[0]!="Stroustrup" )

cout << "Found: " << m[0] << '\n';

给定合适的输入,这将输出 Stroustrup 的拼写错误,例如:

Found: strupstrup

Found: Strovstrup

Found: stroustrub

Found: Stroustrop

请注意,即使模式“隐藏”在其他字符中,regex_search() 也能找到它。例如,它会在 abstrustrubal 中找到 strustrub。如果你想将模式与输入字符串中的每一个字符匹配,请使用 regex_match (§37.3.1)。

37.3.3  regex_replace()

    要对序列的一部分(例如文件)中的模式进行简单替换,请使用 regex_replace():

正则表达式替换(§iso.28.11.4)

匹配由match_flag_type 选项控制(§37.3)

out=regex_replace(out,b,e ,pat,fmt,flags)

将 [b:e) 复制到 out,

搜索正则表达式模式 pat;

当找到 pat 的匹配项时,

使用 fmt 格式将其复制到 out,

由 flags 控制;

fmt 可以是 basic_string 或 C 风格字符串

out=regex_replace(out,b,e ,pat,fmt)

out=reg ex_replace(out,b,e ,pat,fmt,

regex_constants::match_defaults)

s=regex_replace(x,pat,fmt,flags)

将 x 复制到 s,搜索正则表达式模式 pat;

当找到 pat 的匹配项时,使用 fmt 格式将其复制到 s,由标志控制;

x 可以是 basic_string 或 C 风格的字符串;

fmt 可以是 basic_string 或 C 风格的字符串

s=regex_replace(x,pat,fmt)

s=regex_replace(x,pat,fmt,

regex_constants::match_defaults)

复制格式是使用regex的 format() (§37.2.2) 和 $ 前缀符号来完成的,例如,$& 表示匹配,$2 表示第二个子匹配。这里有一个小测试程序,它接受一个包含单词和数字对的字符串,并将它们输出为 {word,number},每行一个:

void test1()

{

string input {"x 1 y2 22 zaq 34567"};

regex pat {"(\w+)\s(\d+)"}; // word space number

string format {"{$1,$2}\n"};

cout << regex_replace(input,pat,format);

}

输出结果是:

{x,1}

{y2,22}

{zaq,34567}

请注意行首那些恼人的“虚假”空格。默认情况下,regex_match() 会将未匹配的字符复制到其输出中,因此 pat 未匹配的两个空格会被打印出来。

       为了消除这些空格,我们可以使用 format_no_copy 选项(§37.2.2):

cout << regex_replace(input,pat,format,reg ex_constants::format_no_copy);

现在,我们得到:

{x,1}

{y2,22}

{zaq,34567}

子匹配不必按顺序输出:

void test2()

{

string input {"x 1 y 2 z 3"};

regex pat {"(\w)\s(\d+)"}; // word space number

string format {"$2: $1\n"};

cout << regex_replace(input,pat,format,reg ex_constants::format_no_copy);

}

我们得到:

1: x

22: y2

34567: zeq

37.4 正则表达式迭代器

   regex_search() 函数允许我们在数据流中查找某个模式的单个匹配项。如果我们想查找并处理所有此类匹配项,该怎么办?如果数据被组织成易于识别的行或记录序列,我们可以迭代这些行或记录,并对每个行或记录使用 regex_match()。如果我们想对每个模式的匹配项执行简单的替换,可以使用 regex_replace()。如果我们想迭代字符序列,并对每个模式的匹配项执行操作,可以使用 regex_iterator。

37.4.1  regex_iterator

    regex_iterator 是一个双向迭代器,当迭代的时候,它在序列中搜索下一个模式匹配项:

template<class Bi,

class C = typename iterator_traits<Bi>::value_type ,

class Tr = typename regex_traits<C>::type>

class regex_iterator {

public:

using regex_type = basic_regex<C,Tr>;

using value_type = match_results<Bi>;

using difference_type = ptrdiff_t;

using pointer = const value_type∗;

using reference = const value_type&;

using iterator_category = forward_iterator_tag;

// ...

}

regex_traits 在§37.5 中有描述。

       提供了常用的别名集:

using cregex_iterator = regex_iterator<const char∗>;

using wcregex_iterator = regex_iterator<const wchar_t∗>;

using sregex_iterator = regex_iterator<string::const_iterator>;

using wsregex_iterator = regex_iterator<wstring::const_iterator>;

regex_iterator 提供了一组最小的迭代器操作:

regex_iterator<Bi,C,Tr> (§iso.28.12.1)

regex_iterator p {};

p 是序列尾

regex_iterator p {b,e,pat,flags);

遍历 [b:e),使用选项标志寻找 pat 的匹配项

regex_iterator p {b,e,pat);

p用{b,e,pat,regex_constants::match_default}  初始化

regex_iterator p {q};

复制构造函数(无移动构造函数)

p=q

赋值构造函数(无移动赋值函数)

p==q

p 是否指向与 q 相同的 sub_match?

p!=q

!(p==q)

c=∗p

c 是当前的 sub_match

x=p−>m

x=(∗p).m

++p

使p 指向p 模式的下一个出现位置

q=p++

q=p, 然后 ++p

regex_iterator 是双向迭代器,因此我们不能直接在 istream 上进行迭代。

    例如,我们可以输出string中所有以空格分隔的单词:

void test()

{

string input = "aa as; asd ++eˆasdf asdfg";

regex pat {R"(\s+(\w+))"};

for (sreg ex_iterator p(input.begin(),input.end(),pat); p!=sregex_iterator{}; ++p)

cout << (∗p)[1] << '\n';

}

输出:

as

asd

asdfg

注意,我们遗漏了第一个单词 aa,因为它前面没有空格。如果我们将模式简化为 R"((\ew+))",我们得到

aa

as

asd

e

asdf

asdfg

你不能通过 regex_iterator 进行写入,并且 regex_iterator{} 是唯一可能的序列尾。

37.4.2  regex_token_iterator

    regex_token_iterator 是 regex_iterator 的适配器,它对找到的 match_results 的 sub_matches 进行迭代:

template<class Bi,

class C = typename iterator_traits<Bi>::value_type ,

class Tr = typename regex_traits<C>::type>

class regex_token_iterator {

public:

using regex_type = basic_regex<C,Tr>;

using value_type = sub_match<Bi>;

using difference_type = ptrdiff_t;

using pointer = const value_type∗;

using reference = const value_type&;

using iterator_category = forward_iterator_tag;

// ...

regex_traits 在§37.5 中有描述。

    常用的别名集如下:

using cregex_token_iterator = regex_token_iterator<const char∗>;

using wcregex_token_iterator = regex_token_iterator<const wchar_t∗>;

using sregex_token_iterator = regex_token_iterator<string::const_iterator>;

using wsregex_token_iterator = regex_token_iterator<wstring::const_iterator>;

regex_token_iterator 提供了一组最小的迭代器操作:

regex_token_iterator (§iso.28.12.2)

regex_token_iterator p {};

p是序列尾

regex_token_iterator p {b,e,pat,x,flags};

x 列出要包含在迭代中的 sub_matche 的索引,或者 0,表示“整个匹配”,或者 -1,表示“将每个未匹配的字符序列表示为 sub_match”;

x 可以是 int、initializer_list<int>、constvector<int>& 或 const int (&sub_match)[N]

regex_token_iterator p {b,e,pat,x};

p 初始化为

{b,e,pat,x,regex_constants::match_default}

regex_token_iterator p {b,e,pat};

p 初始化为

{b,e,pat,0,regex_constants::match_default}

regex_token_iterator p {q};

复制构造函数(无移动构造函数)

p.˜regex_token_iterator()

析构函数:释放所有资源

p=q

复制赋值(无移动赋值)

p==q

p 是否指向与 q 相同的 sub_match?

p!=q

!(p==q)

c=∗p

c 是当前的 sub_match

x=p−>m

x=(∗p).m

++p

让 p 指向 p 模式的下一个出现位置

q=p++

q=p,则 ++p

x 参数列出了要包含在迭代中的sub_match。例如(迭代匹配项 1 和 3):

void test1()

{

string input {"aa::bb cc::dd ee::ff"};

regex pat {R"((\w+)([[:punct:]]+)(\w+)\s∗)"};

sregex_token_iterator end {};

for (sreg ex_token_iterator p{input.begin(),input.end(),pat,{1,3}}; p!=end; ++p)

cout << ∗p << '\n';

}

输出结果:

aa

bb

cc

dd

ee

ff

-1 选项基本上颠倒了报告匹配的策略,将每个不匹配的字符序列表示为一个 sub_match。这通常被称为 token 拆分(即将字符流拆分成 token),因为当你的模式匹配 token 分隔符时,选项 -1 会保留 token。例如:

void test2()

{

string s {"1,2 , 3 ,4,5, 6 7"}; // input

regex pat {R"(\s∗,\s∗)"}; //用逗号作分隔符

copy(sreg ex_token_iterator{s.begin(),s.end(),pat,−1)},

sregex_token_iterator{},

ostream_iterator<string>{cout,"\n"});

}

输出:

1

2

3

4

5

6 7

这可以使用显式循环等效地编写:

void test3()

{

sregex_token_iterator end{};

for (sreg ex_token_iterator p {s.begin(),s.end(),pat,−1}; p!=end; ++p)

cout << ∗p << '\n';

}

37.5  regex_traits

    regex_traits<T> 表示regex实现者所需的字符类型、字符串类型和语言环境之间的对应关系:

template<class C>

struct regex_traits {

public:

using char_type = C;

using string_type = basic_string<char_type>;

using locale_type = locale;

using char_class_type = /* implementation-defined bitmask type */;

// ...

};

标准库提供了特化的 regex_traits<char> 和 regex_traits<wchar_t>。

regex_traits<C>操作(§iso.28.7)

regex_traits tr {};

创建默认的 regex_trait<C>

n=length(p)

n 是 C 风格字符串 p 中的字符数;

n=char_traits<C>::length(); static

c2=tr.translate(c)

c2=c,即无操作

c2=tr.translate_nocase(c)

use_facet<ctype<C>>(getloc()).tolower(c); §39.4.5

s=tr.transform(b,e)

sis 是一个可用于与其他字符串进行比较的字符串[b:e);§39.4.1

s=tr.transform_primary(b,e)

s 是一个字符串,可用于将 [b:e) 与其他字符串进行比较;忽略大小写;§39.4.1

s=tr.lookup_collatename(b,e)

s 是排序元素的string名称(名为 [b:e)]或空字符串

m=tr.lookup_classname(b,e ,ign)

m 是字符分类 [b:e) 的分类掩码的字符串名称;

如果 ign==true,则忽略大小写

m=tr.lookup_classname(b,e)

m=tr.lookup_classname(b,e ,false)

tr.isctype(c,m)

c 是否被归类为 m ?m 是 class_type

i=tr.value(c,b)

iis 是 c 以 b 为底数表示的整数值;

b 必须是 8、10 或 16

loc2=tr.imbue(loc)

将 tr 的本地化设置为 loc;loc2 是 tr 之前的本地化

loc=tr.g etloc()

loc 是 tr 的本地化

转换用于生成字符串,以便在模式匹配实现中进行快速比较。

    分类名称是 §37.1.1 中列出的字符分类之一,例如 alpha、s 和 xdigit。

37.6  建议

[1] 大多数常规正则表达式用法都使用 regex;§37.1。

[2] 正则表达式的表示法可以调整以符合各种标准;§37.1.1,§37.2。

[3] 默认的正则表达式表示法是 ECMAScript 的表示法;§37.1.1。

[4] 为了便于移植,请使用字符类表示法以避免使用非标准缩写;§37.1.1。

[5] 保持克制;正则表达式很容易变成只写语言;§37.1.1。

[6] 除了最简单的模式外,最好使用原始字符串字面量来表达所有模式;§37.1.1。

[7] 请注意, \i 允许你根据前一个子模式来表达子模式;§37.1.1。

[8] 使用 ? 使模式变得“惰性”; §37.1.1,§37.2.1。

[9] regex可以使用 ECMAScript、POSIX、awk、grep 和 egrep 表示法;§37.2。

[10] 保留模式字符串的副本,以备需要输出;§37.2。

[11] 使用 regex_search() 查找字符流,使用 regex_match() 查找固定布局;§37.3.2,§37.3.1。

内容来源:

<<The C++ Programming Language >> 第4版,作者 Bjarne Stroustrup

YOLOv8 置信度阈值 (conf) 和 IoU 阈值 (iou) 详解:如何平衡漏检与误检? 摘要 本文深入探讨了YOLOv8目标检测模型中两个关键参数——置信度阈值(conf)和IoU阈值(iou)的核心作用。文章从目标检测的基础概念出发,解释了置信度分数反映模型预测可靠性,IoU衡量预测框重叠程度。重点剖析了非极大值抑制(NMS)机制如何通过这两个阈值进行预测框筛选:置信度阈值作为初筛门槛,IoU阈值决定重叠框的取舍。通过生动比喻和可视化图表,阐述了合理调节这两个参数能有效平衡误检与漏检问题,是优化YOLOv8模型实际表现的重要技巧。全文以实践为导向,帮助开发者掌握成为"调参大师&qu 阅读详情

相关推荐

Claude Desktop Cowork国内实操指南:本地文件自动化办公

大语言模型正从‘问答式AI’迈向‘执行型协作者’,其核心能力在于直接操作本地文件、调用系统工具并嵌入真实工作流。Claude Desktop的Cowork模式正是这一范式的代表,它通过轻量沙箱VM实现对Excel、PPT、PDF、音视频等办公资产的读写与处理,无需手动编码即可完成数据清洗、会议纪要生成、自动化报告输出等任务。技术价值体现在权限可控、环境隔离、结果可交付;典型场景覆盖行政文秘的文档流转、销售运营的数据分析、开发者的脚本调试与环境验证。本文聚焦国内用户高频卡点——网络链路、系统权限与工作流断层,

weixin_30617737的博客 469

【C++】标准库 — 正则表达式 std::regex

从 C++11 起,标准库增加了正则表达式 (RegularEx)std::regex,包含在头文件中。描述字符序列的方法,用于字符(串)的模式/模糊匹配。用途查找 (是否包含,找出来)标识释义seqsequence 表示目标序列rregex 表示模式,即正则表达式mmatch 对象,即 std::match_results 匹配到结果数组mftmatch flag type 匹配标识选项位掩码类型 (BitmaskType)替换(替换内容,替换格式)标识释义。

Loup&卡普的博客 4395

eDP接口信号组成认识

eDP接口信号主要由Main Link、AUXCH与HPD三部分组成,如下图所示。 Main Link:表示主通道,用来传输各类型视频数据和音频数据; AUX CH:表示辅助通道,用于传输低带宽需求的数据,以及链路管理和设备控制信号; HPD:表示热插拔检测通道。 Main Link南1~4对数据线组成,每对数据线都是一对差分线。对于一款液晶屏而言,Main Link具体需几对数据线,这取决于屏幕的分辨率和彩色位数。 在该通道中传送的信号有视频像素信号、视频定时信号、视频格式信号、比特/像素及

精诚所至 2万+

AAAAABBBBB

AAAAABBBCCCCDDDAAABBBBCCCCCDDDDDAAAAABBBCCCCDDDAAABBBBCCCCCDDDDDAAAAABBBCCCCDDDAAABBBBCCCCCDDDDDAAAAABBBCCCCDDDAAABBBBCCCCCDDDDDAAAAABBBCCCCDDDAAABBBBCCCCCDDDDD

xiaobao007的专栏 29万+

2026年7月19日 从可插拔到共封装:技术路线研究报告

AI 算力的爆发正在重写数据中心光互连的技术路线。本报告对当前并存的四代光互连架构——

weixin_51184047的博客 601

医疗大模型实战——从零构建MedicalGPT全流程解析

本文详细解析了从零构建医疗大模型MedicalGPT的全流程实战。基于Qwen-7B模型与约195万条中文医疗数据,完整复现了增量预训练、监督微调与偏好对齐三大核心环节,并分享了如何在有限硬件资源下实现高效训练与部署,为开发者提供了可复现的医疗AI项目实战指南。

weixin_29193259的博客 558

C++标准库中正则表达式简介

C++标准库中正则表达式的使用                                                                                                   qianghaohao #include #include #include #include #include using namespace s

qhh0205 7623

YOLOv8n轻量化实战:10分钟打通实时摄像头目标检测,附参数调优与避坑指南

本文介绍了如何快速入门YOLOv8目标检测框架,通过摄像头实战实现实时检测。YOLOv8凭借轻量化架构和跨平台优势,是新手入门的理想选择。文章详细讲解了环境搭建(1分钟完成)、核心代码逻辑(3分钟掌握)以及性能调优技巧(3分钟进阶),提供可直接运行的代码示例。重点包括:模型选择(优先yolov8n.pt)、摄像头参数优化、置信度阈值调整、检测类别指定等实用技巧,帮助开发者快速实现10-15FPS的实时检测效果,并针对不同场景提供优化建议。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 375

C++标准库之正则表达式库

目录 1.正则表达式库概述 2.主类   ①类basic_regex   ②类sub_match   ③类match_results 3.算法   ①regex_match   ②regex_search   ③regex_replace 4.迭代器   ①regex_iterator   ②regex_token_iterator 1.正则表达式库概述 ^   正则表...

qq_17044529的博客 3585

GEE:关于遥感生态指数(RSEI)的若干疑问

本文记录了若干关于在 Google Earth Engine (GEE)平台上,计算基于主成分分析(PCA)的遥感生态指数(RSEI)的问题。并记录了解决这些问题的一些答案。问题包括,主成分分析的特征值的正负,主成分的占比,去云后空值像素的处理方法,异常值处理方法,如何看载荷等。

养乐多的博客 3419

2026 最新安全 Skill 合集(CTF / 审计 / 渗透 / 红队)威胁建模一网打尽

2026年安全领域进入"Skill化"时代,各类安全能力被结构化封装为可复用的AI Skill。本文介绍了7个核心安全Skill项目:渗透测试全流程的AgentSkillsHub、CTF解题技能库ctfskills、多语言代码审计工具codeaudit、PHP专项审计系统、Java自动化审计流水线、威胁建模工具threatmodeling以及覆盖30+领域的Anthropic-Cybersecurity-Skills。这些项目将传统安全经验转化为标准化、可验证、可自动执行的模块化能力,支

Chengbei11的博客 1897

C++编程语言:标准库:第36章——字符串类(Bjarne Stroustrup)

C++ 标准库:字符串类

ComputerInBook的专栏 756

机床联网系列总结

总结机床联网专栏,两个好用的工具介绍,以及后续提升的方法和建议。

若云流风的专栏 936

c 程序设计语言标准库,C++程序设计语言(第4部分:标准库)(原书第4版) 中文pdf扫描版[86MB]...

C++语言之父的经典名著之最新版本,全面掌握标准C++11及其编程技术的权威指南!第1版1985年,第2版1991年,第3版1997年,特别版2000年,第4版2013年,经典无限延伸……C++程序设计语言(原书第4版)是在C++语言和程序设计领域具有深远影响、畅销不衰的经典著作,由C++语言的设计者和最初的实现者Bjarne Stroustrup编写,对C++语言进行了最全面、最权威的论述,覆盖...

weixin_35990295的博客 530

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

libstdc++.so.6: cannot open shared object file: No such file or directory

找不到libstdc++.so.6的原因,大致有以下几种: 1.程序中没有编入路径,使用rpath指定路径,在Makefile中加入如下路径: OBJS=*.o ODIR=obj LDFLAGS=-Wl,-rpath=/lib $(ROOT_DIR)/$(BIN_DIR)/$(BIN):$(ROOT_DIR)/$(OBJS_DIR)/$(OBJS) $(CC) $^ -o $@ $(LDFLAGS) 其中/lib为库的路径。 2.由于环境变量的原因,或者是32位或者64位的兼容原因,确实...

ComputerInBook的专栏 1万+

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

c++调用静态函数的方法

今天在写c++程序时,发新现在的gcc和vc++对于静态函数的调用方式有所改变,在旧标准的c++中,调用类的静态方法只能用类名::函数名的方式,在新的标准中,类的对像也可以像调用类的方法一样调用静太函数。示例如下: class Date{ int y,m,d; public: Date(); static void Print(); }; Date::Date() {} void Date::Print() { printf("Hello Worl...

ComputerInBook的专栏 1万+

C语言数组指针加1的问题

指向数组的指针存储的是连续的内存地址,而内存地址的最小编址单位是1字节,如果存储的数据本身移动几个字节,则内存地址也相应地移动几个字节。而数组指针的加1移动几个字节,取决于所指向的数组类型,这部分是由C/C++的编译器实现去处理的。下面具几个例子说明(下面的例子在MSVC的X64平台,指针本身占8个字节): 1. 用C++语言测试 (1) 指向1字节的数组指针: void TestPointerSize() { char data[] = {1,2,3,4,5,6,7,8,9,10}; ...

ComputerInBook的专栏 6045

集合论基本概念——覆盖(cover或covering)

集合论基本概念——覆盖(cover或covering)

ComputerInBook的专栏 4417

在Visual Studio C++ 项目中加入一个汇编语言源文件的方法

1.说明:Visual Studio工程系统通过使用MASM的方式支持在C++项目中使用汇编语言文件。MASM完全支持x64汇编语言源文件, 并自动将它们构建到目标文件中。然后,你可以将这些目标文件链入你为X64平台写的C++代码中。这是克服缺少x64内联汇编器的一种方法(意思就是说克服C++编译器不能直接编译.asm后缀的汇编语言源文件的方法,目前还没有内联支持直接编译汇编语言源文件)。 2.具体步骤 2.1 第一步:按Visual Studio向导建立C++工程,下面重点是第二步。 2.2 第二步:.

ComputerInBook的专栏 3464

集合论基本概念——紧致性(compact或compactness)

集合论:紧致性

ComputerInBook的专栏 3329

linux下编译出现multiple definition of 错误

这个错误从表面上看,是出现了重复定义类或函数的情况,大部分都是确实是重复定义了,但是出现这样的重复定义的原因,即是不太容易获知,我这次出现这样错误,是由于Makefile和操作不当引起的错误。 我是做了这样的操作后出现这种情况的,或许对类似的情况有所启发: 1.编写Makefile文件,正常编译没有问题,编译生成了以下2个文件: client.o v4l2-camara.o 2.这个时候,我把源文件改了个名称,改成了v4l2-camera.cpp,在没有make clean的情况...

ComputerInBook的专栏 2812

c&c++的int和long各自所占字节数

做如下测试: 在windows 64 bit 平台上,使用VC分别编译成32位程序和64位程序,int和long都是占4个字节。 在Linux 64 bit 平台上(测试环境为suse linux,gcc编译器),编译成64位程序,int占4字节,long占8个字节。 因此,int和long到底各占多少字节,是和平台和编译器实现有关。 ...

ComputerInBook的专栏 2322

C++编程语言——基础设施:第7章——指针,数组和引用(Bjarne Stroustrup)

指针,数组和引用

ComputerInBook的专栏 2183

C++编程语言——基础设施:第8章——结构,合并和枚举(Bjarne Stroustrup)

C++: 结构,联合和枚举

ComputerInBook的专栏 2092

Stack cookie instrumentation code detected a stack-based buffer overrun.

在vc++下面出现这个调试错误:Stack cookie instrumentation code detected a stack-based buffer overrun.(栈检测指令检测到基于栈的缓存区被某种操作越界操作了。) 原因:在栈上执行了某种操作,例如,内存复制(memcpy),内存设置(memset),缓冲区格式化(sprintf),等等,查是这个操作已经越过了申请的栈空间的大小。系统在退出函数调用时,会清理栈空音,也就是说,越过函数的结束花括号(})时,就是报以上错误。 要解决以上问题

ComputerInBook的专栏 1946

C++编程语言:基础设施:第10章——表达式(Bjarne Stroustrup)

C++ 表达式和类型转换

ComputerInBook的专栏 1783

C++编程语言:基础设施:第11章——选择运算和类型转换(Bjarne Stroustrup)

C++选择运算和类型转换

ComputerInBook的专栏 1780
上一篇: C++编程语言:标准库:第36章——字符串类(Bjarne Stroustrup)
下一篇: C++编程语言:标准库:第38章——输入输出流(Bjarne Stroustrup)
ComputerInBook
博客等级 码龄19年 1168粉丝 465原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值