在编写处理字符串的程序或网页时,经常会有查找符合某些复杂规则的字符串的需要。正则表达式就是用于描述这些规则的工具。换句话说,正则表达式就是记录文本规则的代码。

很可能你使用过Windows/Dos下用于文件查找的通配符(wildcard),也就是*?。如果你想查找某个目录下的所有的Word文档的话,你会搜索*.doc。在这里,*会被解释成任意的字符串。和通配符类似,正则表达式也是用来进行文本匹配的工具,飞呀(http://www.cnfeiya.com/)只不过比起通配符,它能更精确地描述你的需求——当然,代价就是更复杂——比如你可以编写一个正则表达式,用来查找所有以0开头,后面跟着2-3个数字,然后是一个连字号“-”,最后是7或8位数字的字符串(像010-123456780376-7654321)。

posted @ 2010-03-16 18:45 枫子52011 阅读(342) 评论(0) 编辑
正则其实也势利,削尖头来把钱揣; (指开始符号^和结尾符号$)
特殊符号认不了,弄个倒杠来引路; (指\. \*等特殊符号)
倒杠后面跟小w, 数字字母来表示; (\w跟数字字母;\d跟数字)
倒杠后面跟小d, 只有数字来表示;
倒杠后面跟小a, 报警符号嘀一声;
倒杠后面跟小b, 单词分界或退格;
倒杠后面跟小t, 制表符号很明了;
倒杠后面跟小r, 回车符号知道了;
倒杠后面跟小s, 空格符号很重要;
小写跟罢跟大写,多得实在不得了;
倒杠后面跟大W, 字母数字靠边站;
倒杠后面跟大S, 空白也就靠边站;
倒杠后面跟大D, 数字从此靠边站;
倒框后面跟大B, 不含开头和结尾;
单个字符要重复,三个符号来帮忙; (* + ?)
0 星加1 到无穷,问号只管0 和1; (*表0-n;+表1-n;?表0-1次重复)
花括号里学问多,重复操作能力强; ({n} {n,} {n,m})
若要重复字符串,园括把它括起来; ((abc){3} 表示字符串“abc”重复3次 )
特殊集合自定义,中括号来帮你忙;
转义符号行不通,一个一个来排队;
实在多得排不下,横杠请来帮个忙; ([1-5])
尖头放进中括号,反义定义威力大; ([^a]指除“a”外的任意字符 )
1竖作用可不小,两边正则互替换; (键盘上与“\”是同一个键)
1竖能用很多次,复杂定义很方便;
园括号,用途多;
反向引用指定组,数字排符对应它; (“\b(\w+)\b\s+\1\b”中的数字“1”引用前面的“(\w+)”)
支持组名自定义,问号加上尖括号; (“(?<Word>\w+)”中把“\w+”定义为组,组名为“Word”)
园括号,用途多,位置指定全靠它;
问号等号字符串,定位字符串前面; (“\b\w+(?=ing\b)”定位“ing”前面的字符串)
若要定位串后面,中间插个小于号; (“(?<=\bsub)\w+\b”定位“sub”后面的字符串)
问号加个惊叹号,后面跟串字符串;
PHPer都知道, !是取反的意思;
后面不跟这一串,统统符合来报到; (“\w*d(?!og)\w*”,“dog”不符合,“do”符合)
问号小于惊叹号,后面跟串字符串;
前面不放这一串,统统符合来报到;
点号星号很贪婪,加个问号不贪婪;
加号问号有保底,至少重复一次多;
两个问号老规矩,0次1次团团转;
花括号后跟个?,贪婪变成不贪婪;
还有很多装不下,等着以后来增加
posted @ 2010-02-09 18:44 枫子52011 阅读(841) 评论(1) 编辑

转载请注明来源:枫子整理并发布于:http://www.imfeng.com/iis-rewrite-rules-collect-isapi-rewrite/

二级域名:
RewriteCond Host: (?!/.|www|ww)(.*).gongluela.com
RewriteRule (.*) http/://www.gongluela.com/$1$2 [I,R]

防盗链:
ISAPI_Rewrite的httpd.ini内容写的是下面内容,如果你也遇到盗链的困扰,建议可以参考一下:

RewriteCond Host: (.+)
RewriteCond Referer: (?!http://(?:www\.gongluela\.com|www\.imfeng\.com|www\.goboyo\.com|www\.soso\.com|www\.google\.com|cache\.baidu\.com)).+
RewriteRule .*\.(?:jpg|kmz|kml|zip) /block.gif [I,O]

注释:第二行里面的域名是允许链接图片的网站列表,目前我允许我自己的两个站和另外bloglines、zhuaxia、google、baidu这四个网站引用我站文件,其他网站的引用被禁止。

  第三行是禁止引用的文件类型,包括jpg图片、Google Earth的kmz和kml、zip文件。当然,还可以增加其他类型,比如gif、rar等,因为我站没有那些文件,所以没有添加上去。

下面是转载的一点文章,特转给帅哥看的。

发这个帮助文件是因为在给朋友设置主机的时候发现他们的ISAPI Rewrite的设置都有些不正确,有些甚至阻碍了站点的正常运行。就把官方自带的英文帮助粗略的翻译了一下。大家可以自由使用和转载。但转载时如果你愿意请注明是 蓝色 翻译的版本。

===================
ISAPI Rewrite 配置简介:

在NT/2000/XP和2003平台上,ISAPI Rewrite在系统帐户下射入INETINFO进程与 IIS 以共存模式过滤器运行。所以系统帐户应该给予对ISAPI- REWIRITE DLLS Internet匿名访问组 可读可执行权限 和所有的 HTTPD。INI 文件可读权限,还应该给予系统帐户对于所有包括 HTTPD。INI 文件的文件夹的可写权限,这将允许产生 HTTP。 PARSE。ERRORS 日志文件,来记录配置文件语法错误。对于PROXY模块也需要额外的权限,因为它将运行于连接池或HIGH-ISPLATED 应用模式,IIS帐户共享池和HIGH-ISOLATION池应被给予对RWHELPERE。DLL的可读权限。缺省情况下IWAM-《计算机名》被用于所有的池,在相应的COM+应用设置中应借助COM+ADMINISTRATION MMC SNAP-IN建立池帐户

配置文件格式化:

配置文件分为两种: GLOBAL(服务器全局模式)和 INDIVIDUAL(站点独立设置模式)文件,GLOBAL(服务器端全局模式)配置文件应该被放在ISAPI-REWRITE 安装目录中,名为 httpd.ini 。这个文件可以通过开始菜单的快捷方式访问和配置,这个文件里面的映射规则为全局规则,将针对所有站点起效。INDIVIDUAL(站点独立设置模式)配置文件应该被放在虚拟站点的根目录内,也被命名为httpd.ini文件,这里面应该放置针对站点的映射配置设置,只针对被放置的虚拟站点有效。两种类型的 httpd.ini 都是标准的windows ini 文件。所有的映射规则应该被放置在 [ISAPI_Rewrite] 之后。之前的文件文本将被忽略。
HTTPD.INI文件示例

[ISAPI_Rewrite]

# This is a comment

# 300 = 5 minutes

CacheClockRate 300

RepeatLimit 20

# 设置其他人没有下载 httpd.ini 和 httpd.parse.errors 文件的权限

RewriteRule /httpd(?:\.ini|\.parse\.errors) / [F,I,O]

# Block external access to the Helper ISAPI Extension

RewriteRule .*\.isrwhlp / [F,I,O]

# 配置规则

RewriteCond Host: (.+)

RewriteCond 指令

Syntax:(句法) RewriteCond TestVerb CondPattern [Flags]

这一指令定义一个条件规则,在 RewriteRule 或者 RewriteHeader或 RewriteProxy指令前预行RewriteCond指令,后面的规则只有它的,模式匹配URI的当前状态并且额外的条件也被应用才会被应用。

TestVerb

Specifies verb that will be matched against regular expression.

特别定义的动词匹配规定的表达式

TestVerb=(URL | METHOD | VERSION | HTTPHeaderName: | %ServerVariable) where:

URL – returns Request-URI of client request as described in RFC 2068 (HTTP 1.1);

返回客户端在RFC2068中描述的需求的Request-URI

METHOD – returns HTTP method of client request (OPTIONS, GET, HEAD, POST, PUT, Delete or TRACE);

返回客户端需求(OPTIONS, GET, HEAD, POST, PUT, Delete or TRACE)的HTTP方法

VERSION – returns HTTP version;

返回HTTP版本

HTTPHeaderName – returns value of the specified HTTP header. HTTPHeaderName can be any valid HTTP header name. Header names should include the trailing colon “:”. If specified header does not exists in a client’s request TestVerb is treated as empty string.

返回特定义的HTTP头文件的值

HTTPHeaderName =

Accept:

Accept-Charset:

Accept-Encoding:

Accept-Language:

Authorization:

Cookie:

From:

Host:

If-Modified-Since:

If-Match:

If-None-Match:

If-Range:

If-Unmodified-Since:

Max-Forwards:

Proxy-Authorization:

Range:

Referer:

User-Agent:

Any-Custom-Header

得到更多的关于HTTP头文件的和他们的值的信息参考RFC2068

ServerVariable 返回特定义的服务器变量的值 。例如服务器端口,全部服务器变量列表应在IIS文档中建立,变量名应用%符预定;

CondPattern

The regular expression to match TestVerb

规则表达式匹配TestVerb

[Flags]

Flags is a comma-separated list of the following flags:

O (nOrmalize)

Normalizes string before processing. Normalization includes removing of an URL-encoding, illegal characters, etc. This flag is useful with URLs and URL-encoded headers

RewriteRule 指令

Syntax: RewriteRule Pattern FormatString [Flags]

这个指令可以不止发生一次,每个指令定义一个单独的重写规则,这些规则的定义命令很重要,因为这个命令在应用运行时规则是有用途的

I (ignore case)

不管大小写强行指定字符匹配(http://www.chnjc.com/),这个FLAG影响RewriteRule指令和相应的RewriteCond 指令

F (Forbidden)

对客户端做反应,停止REWRITING进程并且发送403错误,注意在这种情况下FORMATSTRING 是无用的并可以设置为任何非空字符串。

L (last rule)

不应用任何重写规则在此停止重写进程,使用这个FLAG以阻止当前被重写的URI被后面的规则再次重写

N (Next iteration)

强制REWRITINGENGINE调整规则目标并且从头重启规则检查(所有修改将保存),重启次数由RepeatLimit指定的值限制,如果这个数值超过N FLAG将被忽略

NS (Next iteration of the same rule)

以N标记工作不从相同的规则重启规则规则进程(例如强制重复规则应用),通过RepeatLimit指令指定一个反复实行某一规则的最大数目,

P (force proxy)

强制目的URI在内部强制为代理需求并且立即通过ISAPI扩展应付代理需求,必须确认代理字符串是一个有效的URI包括协议主机等等否则代理将返回错误

R (explicit redirect)

强制服务器对客户端发出重定向指示即时应答,提供目的URI的新地址,重定向规则经常是最后规则

RP (permanent redirect)

几乎和[R]标记相同但是发布301HTTP状态而不是302HTTP状态代码

U (Unmangle Log)

当URI是源需求而不是重写需求时记载URI

O (nOrmalize)

在实行之前标准化字符串。标准化包括URL-ENCODING,不合法的字符的再移动等,这个标记对于URLS和URLS-ENDODED头是有用的

CL (Case Lower)

小写

CU (Case Upper)

大写

RewriteHeader directive

Syntax: RewriteHeader HeaderName Pattern FormatString [Flags]

这个指令是RewriteRule的更概括化变种,它不仅重写URL的客户端需求部分,而且重写HTTP头,这个指令不仅用于重写。生成,删除任何HTTP头,甚至改变客户端请求的方法

HeaderName

指定将被重写的客户头(http://www.yaopinwang.org/),可取的值与 RewriteCond 指令中TestVerb参数相同

Pattern

限定规则表达式以匹配Request-URI,

FormatString

限定将生成新的URI的FormatString

[Flags]

是一个下列FLAGS的命令分隔列表

I (ignore case)

不管大小写强行指定字符匹配,这个FLAG影响RewriteRule指令和相应的RewriteCond 指令

F (Forbidden)

对客户端做反应,停止REWRITING进程并且发送403错误,注意在这种情况下FORMATSTRING 是无用的并可以设置为任何非空字符串。

L (last rule)

不应用任何重写规则在此停止重写进程,使用这个FLAG以阻止当前被重写的URI被后面的规则再次重写

N (Next iteration)

强制REWRITINGENGINE调整规则目标并且从头重启规则检查(所有修改将保存),重启次数由RepeatLimit指定的值限制,如果这个数值超过N FLAG将被忽略

NS (Next iteration of the same rule)

以N标记工作不从相同的规则重启规则规则进程(例如强制重复规则应用),通过RepeatLimit指令指定一个反复实行某一规则的最大数目,

R (explicit redirect)

强制服务器对客户端发出重定向指示即时应答,提供目的URI的新地址,重定向规则经常是最后规则

RP (permanent redirect)

几乎和[R]标记相同但是发布301HTTP状态而不是302HTTP状态代码

U (Unmangle Log)

当URI是源需求而不是重写需求时记载URI

O (nOrmalize)

在实行之前标准化字符串。标准化包括URL-ENCODING,不合法的字符的再移动等,这个标记对于URLS和URLS-ENDODED头是有用的

CL (Case Lower)

小写

CU (Case Upper)

大写

 

要重移动头,FORMAT STRING模式应该生成一个空字符串,例如这一规则将从客户请求中重移代理信息

RewriteHeader User-Agent: .* $0

并且这一规则将把OLD-URL HEADER 加入请求中。

RewriteCond URL (.*)RewriteHeader Old-URL: ^$ $1

最后一个例子将通过改变请求方法定向所有的WEBDAV请求到/WEBDAV。ASP

RewriteCond METHOD OPTIONS

RewriteRule (.*) /webdav.asp?$1

RewriteHeader METHOD OPTIONS GET

RewriteProxy directive

Syntax: RewriteProxy Pattern FormatString [Flags]

强制目的URI在内部强制为代理需求并且立即通过ISAPI扩展应付代理需求,这将允许IIS作为代理服务器并且重路由到其他站点和服务器

Pattern

限定规则表达式以匹配Request-URI,

FormatString

限定将生成新的URI的FormatString

[Flags]

是一个下列FLAGS的命令分隔列表

D (Delegate security)

代理模式将试图以当前假冒的用户资格登陆远程服务器,

C (use Credentials)

代理模式将试图一在URL或基本授权头文件中指定的资格登陆远程服务器,用这个标记你可以使用http://user:password@host.com/path/ syntax 作为URL

F (Follow redirects)

缺省情况下ISAPI_Rewrite 将试图将MAP远程服务器返回的重定向指令到本地服务器命名空间,如果远程服务器返回重定向点到那台服务器其他的某个位置,ISAPI_Rewrite 将修改这一重定向指令指向本服务器名,这将避免用户看到真实(内部)服务器名称

使用F标记强制代理模式内部跟踪远程服务器返回的重定向指令,使用这个标记如果你根本不需要接受远程服务器的重定向指令,在WINHTTP设置中有重定向限制以避免远程重定向循环

I (ignore case)

不管大小写强行指定字符匹配

U (Unmangle Log)

当URI是源需求而不是重写需求时记载URI

O (nOrmalize)

在实行之前标准化字符串。标准化包括URL-ENCODING,不合法的字符的再移动等,这个标记对于URLS和URLS-ENDODED头是有用的

CacheClockRate directive

Syntax: CacheClockRate Interval

这个指令只在GLOBAL配置内容中出现,如果这个指令在SITE-LEVEL内容中出现将被忽略并把错误信息写入httpd.parse.errors 文件

ISAPI_Rewrite caches每次在第一次加载时配置(http://www.mshuba.com/),使用这个指令你可以限定当一个特定站点从缓存中清理的不活动周期,把这个参数设置的足够大你可以强制 ISAPI_Rewrite 永不清理缓存,记住任何配置文件的改变将在下次请求后立即更新而忽略这个周期

Interval

限定特定配置被清理出缓存的不作为时间(以秒计),缺省值3600(1小时)

EnableConfig and DisableConfig directives

Syntax:

EnableConfig [SiteID|"Site name"]

DisableConfig [SiteID|"Site name"]

对所选站点激活或不激活SITE-LEVEL配置或者改变缺省配置,缺省SITE-LEVEL配置不激活,这个指令只出现在GLOBAL配置内容中

SiteID

Numeric metabase identifier of a site

Site name

Name of the site as it appears in the IIS console

不用参数使用这个命令将改变缺省配置到ENABLE/DISABLE配置进程

例子

下面例子将使配置仅作用于ID=1(典型是缺省站点)名字是MY SITE的站点

DisableConfig

EnableConfig 1

EnableConfig”My site”

下边例子将激活名称为SOMESITE配置因为它分割设置重载了缺省设置

EnableConfig”Some site”

DisableConfig

EnableRewrite and DisableRewrite directives

Syntax:

EnableRewrite [SiteID|"Site name"]

DisableRewrite [SiteID|"Site name"]

对所选站点激活或不激活重写或者改变缺省配置,缺省重写配置激活,这个指令只出现在GLOBAL配置内容中

SiteID

Numeric metabase identifier of a site

Site name

Name of the site as it appears in the IIS console.

不使用参数这个命令将全部激活或者不激活

RepeatLimit directive

Syntax: RepeatLimit Limit

这个指令可以出现在GLOBAL和SITE-LEVEL配置文件中,如果出现在GLOBAL配置文件中竟改变GLOBAL对于所有站点的限制,出现在SITE-LEVEL配置中竟只改变对于这个站点的限制并且这个限制不能超过GLOBAL限制

ISAPI_Rewrite在实行规则时允许循环,这个指令允许限制最大可能循环的数量,可以设置为0或1而不支持循环,

LIMIT

限制最大循环数量,缺省32

RFStyle directive

Syntax: RFStyle Old | New

Configuration Utility

ISAPI_Rewrite Full包括配置功用(可以在 ISAPI_Rewrite 程序组中启动),它允许你浏览测试状态并输入注册码(如果在安装过程中没有注册),并且调整部分与代理模式操作相关的产品功能,UTILITY是由三个页面组成的属性表

Trial page允许你浏览TIRAL状态并输入注册码(如果在安装过程中没有注册)

Settings page

这页包含对下列参数的编辑框

Helper URL

这个参数影响过滤器和代理模块之间的联系方式,它即可以是以点做前缀的文件扩展名(如 .isrwhlp)也可以是绝对路径,

第一种情况下扩展名将追加在初始请求URI上并且代理模块竟通过SCRIPT MAP激活,缺省扩展名isrwhlp在安装进程中加在global script map 中,如果你改变这个扩展名或者你的应用不继承global script map 设置你应该手动添加向script map 所需求的入口。这个应该有如下参数

Executable: An absolute path to the rwhelper.dll in the short form

Extension: Desired extension (.isrwhlp is default)

Verbs radio button: All Verbs

Script engine checkbox: Checked

Check that file exists checkbox: Unchecked

我们已经创建了一个WSH script proxycfg.vbs ,可以简单在一个a script maps中注册,她位于安装文件夹并且可以在命令行一如下方式运行

cscript proxycfg.vbs [-r] [MetabasePath]

Optional -r 强制注册扩展名

Optional MetabasePath parameter allows specification of the first metabase key to process. By default it is “/localhost/W3SVC”.

要在所有现存的 script maps 中注册你可以以如下命令行激活 script

cscript proxycfg.vbs -r

 

第二种情况下你应该提供一个URI作为’Helper URL’的值(http://www.gongluela.com/),你也应该map 一个 ISAPI_Rewrite的安装文件夹作为美意个站点的虚拟文件家

注意:根据顾客反应,IIS5(也许包括IIS4)对长目录名有问题。所以我们强烈推荐使用短目录名

Worker threads limit

这个参数限制在代理扩展线程池中工作线程数,缺省为0意味着这个限制等于处理器数量乘以2

Active threads limit

这个参数限制当前运行线程数,这个数量不可大于”Worker threads limit”. 缺省0意思是等于处理器数量

Queue size 这个参数定义最大请求数量,如果你曾经看到Queue timeout expired” 信息在 the Application event log中你可以增加这个参数

Queue timeout

这个参数定义你在内部请求队列中防止新请求的最大等待时间,如果你曾经看到Queue timeout expired” 信息在 the Application event log中你可以增加这个参数

Connect timeout

以毫秒设定代理模块连接超时

Send timeout

以毫秒设定代理模块发送超时

Receive timeout

以毫秒设定代理模块发送超时

About page.

It contains copyright information and a link to the ISAPI_Rewrite’s web site.

Regular expression syntax

这一部分覆盖了 ISAPI_Rewrite规定的表达句法

Literals

所有字符都是原意除了 “.”, “*”, “?”, “+”, “(”, “)”, “{”, “}”, “[", "]“, “^” and “$”.,这些字符在用“\”处理时是原意,原意指一个字符匹配自身

Wildcard

The dot character “.” matches any single character except null character and newline character

以下为句法

Repeats

A repeat is an expression that is repeated an arbitrary number of times. An expression followed by “*” can be repeated any number of times including zero. An expression followed by “+” can be repeated any number of times, but at least once. An expression followed by “?” may be repeated zero or one times only. When it is necessary to specify the minimum and maximum number of repeats explicitly, the bounds operator “{}” may be used, thus “a{2}” is the letter “a” repeated exactly twice, “a{2,4}” represents the letter “a” repeated between 2 and 4 times, and “a{2,}” represents the letter “a” repeated at least twice with no upper limit. Note that there must be no white-space inside the {}, and there is no upper limit on the values of the lower and upper bounds. All repeat expressions refer to the shortest possible previous sub-expression: a single character; a character set, or a sub-expression grouped with “()” for example.

Examples:

“ba*” will match all of “b”, “ba”, “baaa” etc.

“ba+” will match “ba” or “baaaa” for example but not “b”.

“ba?” will match “b” or “ba”.

“ba{2,4}” will match “baa”, “baaa” and “baaaa”.

Non-greedy repeats

Non-greedy repeats are possible by appending a ‘?’ after the repeat; a non-greedy repeat is one which will match the shortest possible string.

For example to match html tag pairs one could use something like:

“<\s*tagname[^>]*>(.*?)<\s*/tagname\s*>”

In this case $1 will contain the text between the tag pairs, and will be the shortest possible matching string.

Parenthesis

Parentheses serve two purposes, to group items together into a sub-expression, and to mark what generated the match. For example the expression “(ab)*” would match all of the string “ababab”. All sub matches marked by parenthesis can be back referenced using \N or $N syntax. It is permissible for sub-expressions to match null strings. Sub-expressions are indexed from left to right starting from 1, sub-expression 0 is the whole expression.

Non-Marking Parenthesis

Sometimes you need to group sub-expressions with parenthesis, but don’t want the parenthesis to spit out another marked sub-expression, in this case a non-marking parenthesis (?:expression) can be used. For example the following expression creates no sub-expressions:

“(?:abc)*”

Alternatives

Alternatives occur when the expression can match either one sub-expression or another, each alternative is separated by a “|”. Each alternative is the largest possible previous sub-expression; this is the opposite behaviour from repetition operators.

Examples:

“a(b|c)” could match “ab” or “ac”.

“abc|def” could match “abc” or “def”.

Sets

A set is a set of characters that can match any single character that is a member of the set. Sets are delimited by “[" and "]” and can contain literals, character ranges, character classes, collating elements and equivalence classes. Set declarations that start with “^” contain the compliment of the elements that follow.

Examples:

Character literals:

“[abc]” will match either of “a”, “b”, or “c”.

“[^abc] will match any character other than “a”, “b”, or “c”.

Character ranges:

“[a-z]” will match any character in the range “a” to “z”.

“[^A-Z]” will match any character other than those in the range “A” to “Z”.

Character classes

Character classes are denoted using the syntax “[:classname:]” within a set declaration, for example “[[:space:]]” is the set of all whitespace characters. The available character classes are:

alnum Any alpha numeric character.

alpha Any alphabetical character a-z and A-Z. Other characters may also be included depending upon the locale.

blank Any blank character, either a space or a tab(http://www.xbszgs.com/).

cntrl Any control character.

digit Any digit 0-9.

graph Any graphical character.

lower Any lower case character a-z. Other characters may also be included depending upon the locale.

print Any printable character.

punct Any punctuation character.

space Any whitespace character.

upper Any upper case character A-Z. Other characters may also be included depending upon the locale.

xdigit Any hexadecimal digit character, 0-9, a-f and A-F.

word Any word character – all alphanumeric characters plus the underscore.

unicode Any character whose code is greater than 255, this applies to the wide character traits classes only.

There are some shortcuts that can be used in place of the character classes:

\w in place of [:word:]

\s in place of [:space:]

\d in place of [:digit:]

\l in place of [:lower:]

\u in place of [:upper:]

Collating elements

Collating elements take the general form [.tagname.] inside a set declaration, where tagname is either a single character, or a name of a collating element, for example [[.a.]] is equivalent to [a], and [[.comma.]] is equivalent to [,]. ISAPI_Rewrite supports all the standard POSIX collating element names, and in addition the following digraphs: “ae”, “ch”, “ll”, “ss”, “nj”, “dz”, “lj”, each in lower, upper and title case variations. Multi-character collating elements can result in the set matching more than one character, for example [[.ae.]] would match two characters, but note that [^[.ae.]] would only match one character.

Equivalence classes

Equivalenceclassestakethegeneralform[=tagname=] inside a set declaration, where tagname is either a single character, or a name of a collating element, and matches any character that is a member of the same primary equivalence class as the collating element [.tagname.]. An equivalence class is a set of characters that collate the same, a primary equivalence class is a set of characters whose primary sort key are all the same (for example strings are typically collated by character, then by accent, and then by case; the primary sort key then relates to the character, the secondary to the accentation, and the tertiary to the case). If there is no equivalence class corresponding to tagname, then [=tagname=] is exactly the same as [.tagname.].

To include a literal “-” in a set declaration then: make it the first character after the opening “[" or "[^", the endpoint of a range, a collating element, or precede it with an escape character as in "[\-]“. To include a literal “[" or "]” or “^” in a set then make them the endpoint of a range, a collating element, or precede with an escape character.

Line anchors

An anchor is something that matches the null string at the start(http://www.jiamengku.com/) or end of a line: “^” matches the null string at the start of a line, “$” matches the null string at the end of a line.

Back references

A back reference is a reference to a previous sub-expression that has already been matched, the reference is to what the sub-expression matched, not to the expression itself. A back reference consists of the escape character “\” followed by a digit “1″ to “9″, “\1″ refers to the first sub-expression, “\2″ to the second etc. For example the expression “(.*)\1″ matches any string that is repeated about its mid-point for example “abcabc” or “xyzxyz”. A back reference to a sub-expression that did not participate in any match, matches the null string. In ISAPI_Rewrite all back references are global for entire RewriteRule and corresponding RewriteCond directives. Sub matches are numbered up to down and left to right beginning from the first RewriteCond directive of the corresponding RewriteRule directive, if there is one.

Forward Lookahead Asserts

There are two forms of these; one for positive forward lookahead asserts, and one for negative lookahead asserts:

“(?=abc)” matches zero characters only if they are followed by the expression “abc”.

“(?!abc)” matches zero characters only if they are not followed by the expression “abc”.

Word operators

The following operators are provided for compatibility with the GNU regular expression library.

“\w” matches any single character that is a member of the “word” character class, this is identical to the expression “[[:word:]]”.

“\W” matches any single character that is not a member of the “word” character class, this is identical to the expression “[^[:word:]]”.

“\<” matches the null string at the start of a word.

“\>” matches the null string at the end of the word.

“\b” matches the null string at either the start or the end of a word.

“\B” matches a null string within a word.

Escape operator

The escape character “\” has several meanings.

The escape operator may introduce an operator for example: back references, or a word operator.

The escape operator may make the following character normal, for example “\*” represents a literal “*” rather than the repeat operator.

Single character escape sequences:

The following escape sequences are aliases for single characters:

Escape sequence Character code Meaning

\a 0×07 Bell character.

\t 0×09 Tab character.

\v 0×0B Vertical tab.

\e 0×1B ASCII Escape character.

\0dd 0dd An octal character code, where dd is one or more octal digits.

\xXX 0xXX A hexadecimal character code, where XX is one or more hexadecimal digits.

\x{XX} 0xXX A hexadecimal character code, where XX is one or more hexadecimal digits, optionally a unicode character.

\cZ z-@ An ASCII escape sequence control-Z, where Z is any ASCII character greater than or equal to the character code for ‘@’.

Miscellaneous escape sequences:

The following are provided mostly for perl compatibility, but note that there are some differences in the meanings of \l \L \u and \U:

Escape sequence Meaning

\w Equivalent to [[:word:]].

\W Equivalent to [^[:word:]].

\s Equivalent to [[:space:]].

\S Equivalent to [^[:space:]].

\d Equivalent to [[:digit:]].

\D Equivalent to [^[:digit:]].

\l Equivalent to [[:lower:]].

\L Equivalent to [^[:lower:]].

\u Equivalent to [[:upper:]].

\U Equivalent to [^[:upper:]].

\C Any single character, equivalent to ‘.’.

\X Match any Unicode combining character sequence, for example “a\x 0301″ (a letter a with an acute).

\Q The begin quote operator, everything that follows is treated as a literal character until a \E end quote operator is found.

\E The end quote operator, terminates a sequence begun with \Q.

What gets matched?

The regular expression will match the first possible matching string, if more than one string starting at a given location can match then it matches the longest possible string. In cases where their are multiple possible matches all starting at the same location, and all of the same length, then the match chosen is the one with the longest first sub-expression, if that is the same for two or more matches, then the second sub-expression will be examined and so on. Note that ISAPI_Rewrite uses MATCH algorithm. The result is matched only if the expression matches the whole input sequence. For example:

RewriteCond URL ^/somedir/.* #will match any request to somedir directory and subdirectories, while

RewriteCond URL ^/somedir/ #will match only request to the root of the somedir.

Special note about “pathological” regular expressions

ISAPI_Rewrite uses a very powerful regular expressions engine Regex++ written by Dr. John Maddock. But as any real thing it’s not ideal: There exists some “pathological” expressions which may require exponential time for matching; these all involve nested repetition operators, for example attempting to match the expression “(a*a)*b” against N letter a’s requires time proportional to 2N. These expressions can (almost) always be rewritten in such a way as to avoid the problem, for example “(a*a)*b” could be rewritten as “a*b” which requires only time linearly proportional to N to solve. In the general case, non-nested repeat expressions require time proportional to N2, however if the clauses are mutually exclusive then they can be matched in linear time – this is the case with “a*b”, for each character the matcher will either match an “a” or a “b” or fail, where as with “a*a” the matcher can’t tell which branch to take (the first “a” or the second) and so has to try both.

Boost 1.29.0 Regex++ could detect “pathological” regular expressions and terminate theirs matching. When a rule fails ISAPI_Rewrite sends “500 Internal Server error – Rule Failed” status to a client to indicate configuration error. Also the failed rule is disabled to prevent performance losses

Format string syntax

In format strings, all characters are treated as literals except: “(”, “)”, “$”, “\”, “?”, “:”.

To use any of these as literals you must prefix them with the escape character \

The following special sequences are recognized:

Grouping:

Use the parenthesis characters ( and ) to group sub-expressions within the format string, use \( and \) to represent literal ‘(’ and ‘)’.

Sub-expression expansions:

The following perl like expressions expand to a particular matched sub-expression:

$` Expands to all the text from the end of the previous match to the start of the current match, if there was no previous match in the current operation, then everything from the start of the input string to the start of the match.

$’ Expands to all the text from the end of the match to the end of the input string.

$& Expands to all of the current match.

$0 Expands to all of the current match.

$N Expands to the text that matched sub-expression N.

Conditional expressions:

Conditional expressions allow two different format strings to be selected dependent upon whether a sub-expression participated in the match or not:

?Ntrue_expression:false_expression

Executes true_expression if sub-expression N participated in the match, otherwise executes false_expression.

Example: suppose we search for “(while)|(for)” then the format string “?1WHILE:FOR” would output what matched, but in upper case

Escape sequences:

The following escape sequences are also allowed:

\a The bell character.

\f The form feed character.

\n The newline character.

\r The carriage return character.

\t The tab character.

\v A vertical tab character.

\x A hexadecimal character – for example \x0D.

\x{} A possible unicode hexadecimal character – for example \x{1A0}

\cx The ASCII escape character x, for example \c@ is equivalent to escape-@.

\e The ASCII escape character.

\dd An octal character constant, for example \10

Examples例子

Emulating host-header-based virtual sites on a single site

例如你在两个域名注册www.gongluela.comwww.jiamengku.com,现在你可以创建两个不同的站点而使用单一的物理站点。把以下规则加入到你的httpd.ini 文件

[ISAPI_Rewrite]

#Fix missing slash char on folders

RewriteCond Host: (.*)

RewriteRule ([^.?]+[^.?/]) http\://$1$2/ [I,R]

#Emulate site1

RewriteCond Host: (?:www\.)?site1\.com

RewriteRule (.*) /site1$1 [I,L]

#Emulate site2

RewriteCond Host: (?:www\.)?site2\.com

RewriteRule (.*) /site2$1 [I,L]

现在你可以把你的站点放在/site1 和 /site2 目录中.

或者你可以应用更多的类规则:

[ISAPI_Rewrite]

#Fix missing slash char on folders

RewriteCond Host: (.*)

RewriteRule ([^.?]+[^.?/]) http\://$1$2/ [I,R]

RewriteCond Host: (www\.)?(.+)

RewriteRule (.*) /$2$3

为站点应该命名目录为 /somesite1.com, /somesite2.info, etc.

Using loops (Next flag) to convert request parameters

假如你希望有物理URL如 http://www.myhost.com/foo.asp?a=A&b=B&c=C 使用请求如 http://www.myhost.com/foo.asp/a/A/b/B/c/C 参数数量可以从两个请求之间变化

至少有两个解决办法。你可以简单的为每一可能的参数数量添加一个分隔规则或者你可以使用一个技术说明如下面的例子

ISAPI_Rewrite]

RewriteRule (.*?\.asp)(\?[^/]*)?/([^/]*)/([^/]*)(.*) $1(?2$2&:\?)$3=$4$5 [NS,I]

这个规则将从请求的URL中抽取一个参数追加在请求字符的末尾并且从头重启规则进程。所以它将循环直到所有参数被移动到适当的位置,或者直到超过RepeatLimit

也存在许多这个规则的变种。但使用不同的分隔字符,例如。使用URLS如http://www.myhost.com/foo.asp~a~A~b~B~c~C 可以应中下面的规则:

ISAPI_Rewrite]

RewriteRule (.*?\.asp)(\?[^~]*)?~([^~]*)~([^~]*)(.*) $1(?2$2&:\?)$3=$4$5 [NS,I]

Running servers behind IIS

假如我们有一个内网服务器运行IIS而几个公司服务器运行其他平台,这些服务器不能从INTERNET直接进入,而只能从我们公司的网络进入,有一个简单的例子可以使用代理标记映射其他服务器到IIS命名空间:

[ISAPI_Rewrite]

RewriteProxy /mappoint(.+) http\://sitedomain$1 [I,U]

Moving sites from UNIX to IIS

这个规则可以帮助你把URL从 /~username 改变到 /username 和从 /file.html 改变到 /file.htm. 这个在你仅仅把你的站从UNIX移动到IIS并且保持搜索引擎和其他外部页面对老页面的连接时是有用的

[ISAPI_Rewrite]

#redirecting to update old links

RewriteRule (.*)\.html $1.htm

RewriteRule /~(.*) http\://myserver/$1 [R]

Moving site location

许多网管问这样的问题:他们要重定向所有的请求到一个新的网络服务器,当你需要建立一个更新的站点取代老的的时候经常出现这样的问题,解决方案是用ISAPI_Rewrite 于老服务器中

[ISAPI_Rewrite]

#redirecting to update old links

RewriteRule (.+) http\://newwebserver$1 [R]

Browser-dependent content

Dynamically generated robots.txt

robots.txt是一个搜索引擎用来发现能不能被索引的文件,但是为一个大站创建一个有许多动态内容的这个文件是很复杂的工作,我们可以写一个robots.asp script

现在使用单一规则生成 robots.txt

[ISAPI_Rewrite]

RewriteRule /robots\.txt /robots.asp

Making search engines to index dynamic pages

站点的内容存储在XML文件中,在服务器上有一个/XMLProcess.asp 文件处理XML文件并返回HTML到最终用户,URLS到文档有如下形式

http://www.mysite.com/XMLProcess.asp?xml=/somdir/somedoc.xml

但是许多公共引擎不能索引此类文档,因为URLS包含问号(文档动态生成),

ISAPI_Rewrite可以完全消除这个问题

[ISAPI_Rewrite]

RewriteRule /doc(.*)\.htm /XMLProcess.asp\?xml=$1.xml

现在使用如同http://www.mysite.com/doc/somedir/somedoc.htm的URL进入文档,搜索引擎将不知道不是somedoc.htm 文件并且内容是动态生成的

Negative expressions (NOT

有时当模式不匹配你需要应用规则,这种情况下你可以使用在规则表达式中称为Forward Lookahead Asserts

例如你需要不使用IE把所有用户移动到别的地点

[ISAPI_Rewrite]

# Redirect all non Internet Explorer users

# to another location

RewriteCond User-Agent: (?!.*MSIE).*

RewriteRule (.*) /nonie$1

Dynamic authentification

例如我们在站点上有一些成员域,我们在这个域上需要密码保护文件而我们不喜欢用BUILT-IN服务器安全,这个情况下可以建立一个ASP脚本(称为proxy.asp),这个脚本将代理所有请求到成员域并且检查请求允许,这里有一个简单的模板你可以放进你自己的授权代码

现在我们要通过配置 ISAPI_Rewrite 通过这个页面代理请求:

[ISAPI_Rewrite]

# Proxy all requests through proxy.asp

RewriteRule /members(.+) /proxy.asp\?http\://mysite.com/members$1

保护图片 防止盗链
Blocking inline-images (stop hot linking

假设我们在http://www.mysite.com/下有些页面调用一些GIF、jpg、png图片,不允许别人盗链引用到他们自己的页面上,因为这样大大增加了服务器流量。
当然我们不能100%保护图片,但我们至少可以在得到浏览器发出的HTTP Referer header的地方限制这种情况,因为这个可以判断是否我们自己的站点调用了我们自己的图片。

[ISAPI_Rewrite]

RewriteCond Host: (.+)

RewriteCond Referer: (?!http://\1.*).*

RewriteRule .*\.(?:gif|jpg|png) /block.gif [I,O]

注:ISAPI_Rewrite分精简(Lite)和完全(Full)版.精简版不支持对每个虚拟主机站点进行重写,只能进行全局处理.不过对于有服务器的朋友,精简版也就够啦.精简版下载地址:http://www.helicontech.com/download/,就是那Lite Version (free)啦。

posted @ 2010-02-04 03:25 枫子52011 阅读(465) 评论(0) 编辑
 

云计算目前正在稳定而缓慢向企业进军,其主要是作为测试和研发环境以及作为一些不重要的应用和服务的平台。不过,这篇文章云计算厂商正在努力扩大战果,让其作为重要商业应用的平台。为此,他们已经解决标准和安全问题,提高服务等级协议,鼓励厂商认同基于软件使用的定价原则。

基于以上的背景,2010年将有更多的企业开始应用云计算,以下是2010年云计算的十大趋势。

商品云价格将继续降价

在今年11月份,亚马逊EC2降价15%。一个小型标准化基于Linux的云计算服务费用由原来的每小时10美分降价为8.5美元。同样在11月份,谷歌将其Picasa照片存储价格费用由一年20美元降价至一年5美元。基于云的应用也纷纷开始降价。微软的Business Productivity Online Suite(企业网络服务套装)的收费标准由每用户每月15美元下调至了10美元。不过,谷歌的Apps Premier Edition的收费标准仍然保持在一年50美元。Web服务咨询公司Roundarch的首席执行官Jeff Maling表示:“云计算的费用正在下降。为了让云计算得到大规模应用,云计算厂商已经开始大幅降价。”

将采用更为简单的云计算定价模式

由于供应商开始提供更多的选择和服务,定价模式正变得越来越复杂。以亚马逊为例(http://www.yjslc.cn/),它们有一个计算机专门用来评估带宽传输、负载平衡和弹性IP的成本。2010年,越来越我的云计算服务供应商可能会采用“自助餐定价模式”。IT服务与咨询公司CSS的远程基础设施管理副总裁Ahmar Abbas称:“在自助餐定价模式中,用户将通过合同为一系列服务进行包时。”

企业应用厂商将采用计量计费模式

这一点或许无法在2010年实现,原因在于很难让应用厂商放弃先前的诸如席位或设置单独用户的访问权限的许可证和营收模式转而支持计量计费模式。尽管如此,基于使用的计量计费模式将会对诸如Accelera Solutions等公司带来帮助。Accelera公司总裁Joe Brown表示,Falls Church公司已经为此推出了大量的软件工具,这些工具用于不同的许可证配置方案,基本设置统一收费为每月25美元。他相信,厂商会适应这种计费模式。

Brown称:“他们都已经意识到云计算将促进他们的业务发展。”支持计量计费模式的行业观察人士相信,这一模式还将会促进测量使用量的技术进行提高,或许明年可能会取得一定的成绩。不过目前,云计算提供商需要与客户进行谈判。

云提供商将逐渐提供企业级SLA

99.9%和100%的正常运行对于云计算厂商来说就意味着市场。正常运行保证并不意味着云计算提供商有能力达到重要业务的需求。性能监测公司Lexington的首席技术官Imad Mouline表示,客户希望知道云计算厂商将否快速的将他们在美国东海岸做的东西传递到美国西海岸。他们的网络连接状况好的什么程度?Mouline称:“IT经理人希望他们与云计算提供商签订服务等级协议(SLA)能够让他们在晚上睡的安稳。否则,云计算只是一个好看而不中用的小沙盒。”换句话说,云计算主要是作为应用测试和研发的平台。

新技术将提高云计算的使用和性能

Riverbed技术公司正在将硬件工具与虚拟系统相结合提供核心服务。该公司计划在2010年的某一个时间推出该产品。这一趋势将吸引第三方为云环境改变数据中心技术,其中包括减少板载成本的工作或将应用移植到云上的工具。

posted @ 2010-01-16 03:16 枫子52011 阅读(368) 评论(0) 编辑

本节课将介绍如何使用C#选择控制语句,第三课将达到如下几个目的:
1.学会"if"语句的用法。

2.学会"switch"语句的用法。

3.学会在"switch"语句中如何使用"break"语句。

4.理解"goto"语句的正确用法。

在前面几节课中,你所看到的程序都是顺序执行的。你无法控制输入语句,你所能做的就是跟着程序执行直到终止。本节课中,将介绍基于条件进行判断,从而选择进入相应的逻辑分支中去执行。

我们所介绍的第一个选择语句是"if"语句,它有三种基本形式:单条选择, 如果/否则,以及多情形选择。

1.清单3-1. IF语句的格式:IfSelection.cs

using System;
class IfSelect {
public static void Main() {
string myInput;
int myInt;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
// Single Decision and Action with brackets
if (myInt > 0) {
Console.WriteLine("Your number {0} is greater than zero.", myInt);
}
// Single Decision and Action without brackets
if (myInt < 0)
Console.WriteLine("Your number {0} is less than zero.", myInt);
// Either/Or Decision
if (myInt != 0) {
Console.WriteLine("Your number {0} is not equal to zero.", myInt);
}
else {
Console.WriteLine("Your number {0} is equal to zero.", myInt);
}
// Multiple Case Decision
if (myInt < 0 || myInt == 0) {
Console.WriteLine("Your number {0} is less than or equal to zero.", myInt);
}
else if (myInt > 0 && myInt <= 10) {
Console.WriteLine("Your number {0} is between 1 and 10.", myInt);
}
else if (myInt > 10 && myInt <= 20) {
Console.WriteLine("Your number {0} is between 11 and 20.", myInt);
}
else if (myInt > 20 && myInt <= 30) {
Console.WriteLine("Your number {0} is between 21 and 30.", myInt);
}
else {
Console.WriteLine("Your number {0} is greater than 30.", myInt);
}
}
}

说明


1.清单3-1中的IF语句的各种格式都使用了同一个输入变量"myInt"。

这是从用户获得交互内容的另一种方式。我们首先输出一行信息:"Please enter a number:"到控制台。"Console.ReadLine()"语句使得程序等待来自用户的输入,一旦用户输入一个数字,按回车键之后,该数字以字符串的形式返回到"myInput"变量中,由于我们需要的是一个整数,所以需要转换变量"myInput"成整型数据。用命令"Int32.Parse(myInput)"即可完成。 (Int32 等数据类型将在后面的课程中加以介绍。) 转换结果放到"myInt"变量中,这是个整数类型。

 

2.有了我们所需要的类型的数据,就可以用"if"语句来进行条件判断了。

对于第一种形式的IF语句,格式为: if (boolean expression) { statements }。该语句必须以关键字"if"开始。之后,括号中为布尔表达式。该布尔表达式必须计算出一个true或者false值。在本例中,我们检查用户的输入,看看输入值是否大于0,如果表达式运算结果为true,就执行大括号中的语句。(我们把大括号之间的语句部分称为"block"。) 块中有一个或者多个语句。如果布尔表达式的值为false,我们就忽略块中的语句,直接执行块后面的语句。

3.除了没有块之外,第二种"if"语句的格式非常类似于第一种。

因此,如果布尔表达式为true,将会执行布尔表达式之后的第一条语句。当布尔表达式的值为false,布尔表达式之后的第一条语句将被忽略掉,而直接执行其后的程序语句。如果你只有一条语句需要执行,就用该格式的"if"语句。如果你打算在布尔表达式的值为true时,执行两条或者两条以上的语句,就必须把它们放到块中。我个人的建议是:无论需要执行几条语句,要养成把if语句放到块中的习惯, 这就使得你避免犯如下错误:当添加了一条语句之后,忘记了添加一对括号。

4.大多数时候,你需要作出如下选择:当条件满足时做一件事,否则做另外一件事。

清单3-1中,程序演示了这种if语句格式的用法。 当布尔表达式为true时, 就立刻执行"if"后面的那条语句, 而当布尔表达式为false时,就执行"else"关键字后面的语句。

5.当要计算多个布尔表达式时,你可以使用if/else if/else 这种格式,上面的例子程序演示了这种形式,从关键字"if"开始, 一旦布尔表达式为真,就执行if后面的块。但是,这一次,在组合关键字"else if"后面还可以进行多个条件的判断。"else if"语句后面也有个布尔表达式,一旦该布尔表达式的值为true,就会执行紧接其后的块。这种情形可以一直持续下去,直到所有的情况都已经计算出来,但是整个"if/else if"序列必须以"else"结束。当所有的"if"或者"else if" 后面的布尔表达式的值都为false时,就执行关键字"else"后面的块。 对于if/else if/else格式的语句,每次仅仅执行一个其中部分的语句 。

6.上面的例子中,布尔表达式 (myInt < 0 || myInt == 0)包含了条件OR (||)运算符。

对于常规OR (|)运算符和条件OR (||)运算符来说,只要有运算符两边的子表达式之一为真,整个布尔表达式的值就为真。两个运算符的区别在于:正规OR 运算符(|)每次都对运算符(|)两边的表达式进行计算。而条件运算符OR (||)只有当第一个子表达式的值为false时,才计算第二个子表达式的值。

7.布尔表达式 (myInt > 0 && myInt <= 10)包含了条件运算符AND。

对于常规AND (&) 运算符和条件AND (&&)运算符来说,只有游龙戏凤当运算符两边的子表达式的值都为真时,整个布尔表达式的值为真。两种运算符的区别在于:正规AND (&)运算符每次都计算运算符两边的子表达式的值,但是对于条件AND运算符来说,只有当第一个子表达式的值为真时,才计算第二个表达式的值。条件运算符(&& 和 ||) 通常称为运算优化的运算符,因为有时不需要计算整个表达式的值。这样就可以忽略掉不必要的逻辑表达式的计算,可以生成有效的代码。

同if/else if/else 格式的"if"语句类似,"switch"语句的用法如下:

2.清单3-2. 分支选择语句: SwitchSelection.cs

using System;
class SwitchSelect {
public static void Main() {
string myInput;
int myInt;

begin:
Console.Write("Please enter a number between 1 and 3: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
// switch with integer type
switch (myInt) {
case 1:
Console.WriteLine("Your number is {0}.", myInt);
break;
case 2:
Console.WriteLine("Your number is {0}.", myInt);
break;
case 3:
Console.WriteLine("Your number is {0}.", myInt);
break;
default:
Console.WriteLine("Your number {0} is not between 1 and 3.", myInt);
}

decide:
Console.Write("Type \"continue\" to go on or \"quit\" to stop: ");
myInput = Console.ReadLine();
// switch with string type
switch (myInput) {
case "continue":
goto begin;
case "quit":
Console.WriteLine("Bye.");
break;
default:
Console.WriteLine("Your input {0} is incorrect.", myInput);
goto decide;
}
}
}

说明

1.清单3-2 演示了多分支选择语句switch的用法。

关键字"switch"后面是switch 表达式。Switch表达式必须是以下类型中的一种: sbyte,byte,short,ushort, int,uint,long,ulong,char,string,或者enum类型。(enum类型将在后面的课程中加以介绍)。在清单3-2的第一个"switch"语句中, switch 表达式计算的是整数类型的数据。

2.在switch表达式后面是个switch 块, 当Switch表达式的值同某一个case后面的常量表达式的值相匹配时,就执行此case后面的语句,直到遇到"break"语句或者"goto"语句为止。每个分支以关键字"case"作为标号,其后为常量表达式,然后是分号(:)。本例子程序中,我们有"case 1:","case 2:"和"case 3:"。

3.你可以在所有的分支选择的后面加上一个"default"分支。

如果没有匹配的常量表达式,就进入default分支,并执行该分支的七磅语句。虽然default标号是可选的,我建议你加上该分支。这将有助于处理一些意外事件 ,使得你的程序能够捕捉和处理不可预见的事件,从而使得程序更加可靠。

4.每个"case"标号必须以"break"语句作为结束。

"break"语句将使得程序退出switch语句,并从switch块后面的一条语句开始执行。对于"default"标号来说,"break"语句是可选的,因为有"break"语句和没有"break"语句,其运行结果是一样的。如果你在switch块中放置了一个"goto"语句,情况就不一样了。

5.清单3-2中的第二个"switch"语句演示了"goto"语句的用法。

"goto"语句可以让程序跳到关键字"goto"后面的标号中去执行。程序执行过程中,如果用户打入"continue", switch语句就匹配case "continue" 中的常量表达式,并执行"goto begin:"语句。程序就会离开"switch"语句,开始执行标号"begin:"后的第一条语句。这是个有效的循环,可以让你多次重复执行同样一段代码。一旦用户打入字符串"quit",循环将会结束。此时,将进入case "quit" 分支。该分支将输出信息"Bye."到控制台上,之后跳出switch语句,再结束程序。

一旦输入的字符串既不是"continue"也不是"quit",就会进入"default:"分支。于是,将会输出一个出错信息到控制台上,之后执行"goto decide:"命令。这就使得程序转跳到"decide:" 标号后面的第一条语句, 该语句执行后,将会询问用户是否愿意continue(继续)还是 quit(退出)。这是个有效的循环。

显然,"goto"语句功能强大,在受控的场合下,"goto"语句是很有用途的。但是,必须指出的是,"goto"如果出现被滥用的趋势,程序的调试和维护将会变得很困难。想象一下,如果程序到处可见goto语句,其流程将会变得难以阅读和理解。下节课中,将介绍在程序中创建循环语句的更好方法。

小结
现在,你已经了解了如何使用"if"语句的各种格式,也了解了如何使用"switch"语句。你也了解了使用"break"语句可以从"switch"语句中推出。最后,你也了解了如何使用"goto"语句跳到程序的另外一个部分。

posted @ 2009-01-15 06:29 枫子52011 阅读(59) 评论(0) 编辑

逻辑与 &
逻辑异或 ^
逻辑或 |
条件与 &&
条件或 ||
条件 ?:
赋值等 = *= /= %= += -= <<= >>= &= ^= |=

左结合意味着运算符是从左到右进行运算的。右结合意味着所有的运算是从右到左进行的,如赋值运算符,要等到其右边的计算出来之后,才把结果放到左边的变量中。

2.清单 1-2. 单目运算符: Unary.cs

using System;
class Unary {
public static void Main() {
int unary = 0;
int preIncrement;
int preDecrement;
int postIncrement;
int postDecrement;
int positive;
int negative;
sbyte bitNot;
bool logNot;
preIncrement = ++unary;
Console.WriteLine("Pre-Increment: {0}", preIncrement);
preDecrement = --unary;
Console.WriteLine("Pre-Decrement: {0}", preDecrement);
postDecrement = unary--;
Console.WriteLine("Post-Decrement: {0}", postDecrement);
postIncrement = unary++;
Console.WriteLine("Post-Increment: {0}", postIncrement);
Console.WriteLine("Final Value of Unary: {0}", unary);
positive = -postIncrement;
Console.WriteLine("Positive: {0}", positive);
negative = +postIncrement;
Console.WriteLine("Negative: {0}", negative);
bitNot = 0;
bitNot = (sbyte)(~bitNot);
Console.WriteLine("Bitwise Not: {0}", bitNot);
logNot = false;
logNot = !logNot;
Console.WriteLine("Logical Not: {0}", logNot);
}
}

说明


1.当计算表达式的时候,在后置增一和后置减一运算符进行运算时,先返回其值,再进行增一或者减一运算。当使用前置加号和减号运算符进行运算时,是先进行增一或者减一的运算,然后再返回其结果值。

2.在清单1-2中, 变量unary初始化为0,进行++x 运算时,"unary"的值加1,再把其值1赋给"preIncrement"变量。在进行--x运算时,先把"unary"的值减到0, 再把值0赋给"preDecrement"变量。

3.进行x-运算时,先把"unary"的值0赋给"postDecrement" 变量,之后再把"unary"减到-1。进行x++运算时,先把"unary"的值-1赋给"postIncrement"变量,之后再对"unary"加1,使得"unary"变量现在的值为0。

4.变量"bitNot"初始值为0,进行按位取反运算,本例中,数0表示为二进制"00000000",按位取反之后变为-1,其二进制表示为"11111111"。

5.了解一下表达式"(sbyte)(~bitNot)", 任何对类型sbyte, byte, short 或者 ushort 类型数据的运算,返回结果都是整数。要把值赋给bitNot变量,我们必须使用cast (类型)运算符(强制类型转换),其中Type表示你希望转换成的类型(本例中为sbyte)。 Cast运算符把大范围类型的数据转换为小范围类型的数据时,须特别谨慎,因为此时有丢失数据的危险。一般来说,把小类型的数据赋给大类型变量,并没有问题, 因为大范围数据类型的变量具有足够的空间存放小类型数据。 注意在signed 和unsigned类型之间进行Cast运算时,也存在此类危险。 许多初级程序设计教程对变量的位表示作出了很好的讲解,同时也介绍了直接进行Cast运算的危险。

 

逻辑非(!)运算符可以处理布尔变量值。本例中,"logNot"变量从false 变为true。

上述程序的输出结果如下:

>Pre-Increment: 1
>Pre-Decrement 0
>Post-Decrement: 0
>Post-Increment -1
>Final Value of Unary: 0
>Positive: 1
>Netative: -1
>Bitwise Not: -1
>Logical Not: True

3.清单 1-3. 二元运算符 Binary.cs

using System;
class Binary {
public static void Main() {
int x, y, result;
float floatResult;
x = 7;
y = 5;
result = x+y;
Console.WriteLine("x+y: {0}", result);
result = x-y;
Console.WriteLine("x-y: {0}", result);
result = x*y;
Console.WriteLine("x*y: {0}", result);
result = x/y;
Console.WriteLine("x/y: {0}", result);
floatResult = (float)x/(float)y;
Console.WriteLine("x/y: {0}", floatResult);
result = x%y;
Console.WriteLine("x%y: {0}", result);
result += x;
Console.WriteLine("result+=x: {0}", result);
}
}

说明


清单1-3 演示了二元操作符的几个例子。加法(+),减法(-),乘法(*)和除法(/)的运算结果,就是我们通常进行的的四则运算的结果。

因为"floatResult"变量是浮点运算类型,所以整型变量"x"和"y" 被强制转换成浮点类型来计算FloatResult。

这里有个求余数的运算符,两个操作数相除,返回余数。

最后一条语句给出了另外一种赋值形式,这里用了(+=)运算符.无论什么时候你使用(+=)运算符,那么这个二进制运算符就应该在运算符左右两边都进行运算,然后把值赋给左边的参数。本语句相当于"result = result + x",并返回七磅同样的值。

前面的课程中,你看到的使用次数较多的一种类型是"string" (字符串)类型。"string"类型是由包含在引号内的Unicode编码的字符构成。例如"This is a string."

另外一种数据类型是数组。数组可以看成是同种类型的元素构成的集合。当声明数组时,你要指定类型名,数组名,维数和数组大小。

4.清单 1-4. Array Operations: Array.cs

using System;
class Array {
public static void Main() {
int[] myInts = { 5, 10, 15 };
bool[][] myBools = new bool[2][];
myBools[0] = new bool[2];
myBools[1] = new bool[1];
double[,] myDoubles = new double[2, 2];
string[] myStrings = new string[3];
Console.WriteLine("myInts[0]: {0}, myInts[1]: {1}, myInts[2]: {2}", myInts[0], myInts[1], myInts[2]);
myBools[0][0] = true;
myBools[0][1] = false;
myBools[1][0] = true;

Console.WriteLine("myBools[0][0]: {0}, myBools[1][0]: {1}", myBools[0][0], myBools[1][0]);
myDoubles[0, 0] = 3.147;
myDoubles[0, 1] = 7.157;
myDoubles[1, 1] = 2.117;
myDoubles[1, 0] = 56.00138917;
Console.WriteLine("myDoubles[0, 0]: {0}, myDoubles[1, 0]: {1}", myDoubles[0, 0], myDoubles[1, 0]);
myStrings[0] = "Joe";
myStrings[1] = "Matt";
myStrings[2] = "Robert";
Console.WriteLine("myStrings[0]: {0}, myStrings[1]: {1}, myStrings[2]: {2}", myStrings[0], myStrings[1], myStrings[2]);
}
}

说明

清单 1-4 演示了数组的各种不同实现方法。第一个例子是"myInts"数组,它在声明的同时进行了初始化。

接着是个二维数组,可以把它理解为数组的数组。我们需要使用"new"运算符来实例化初始数组的大小,之后,再对每个子数组使用new运算符。

第三个例子是个二维数组。数组可以是多维的,每一维可以通过逗号隔开,也必须用"new"运算符进行实例化。

最后定义了一个一维的字符串数组。

每种情况下,对于数据元素的访问可以通过引用元素的位置(下标)来进行。数组的大小可以是任何整型值。其下标从0开始。

小结
到现在为止,你已经了解了C# 的变量,简单数据类型,数组和字符串。我们还学习了如何用C#的运算符构成表达式。 不知道大家有没有真正学到什么呢?

posted @ 2009-01-15 06:27 枫子52011 阅读(92) 评论(0) 编辑

在本文开始写作的时候,虽然商用C# 编译器尚未推出, 但你可以下载微软的.NET Frameworks SDK Beta 1.
本节课通过介绍几个简单的程序,使得你对C#有所入门。本节程要达到如下几个目的:
1.理解一个C#程序的基本结构。

2.初步了解"名称空间"的概念。

3.初步了解"类"的概念。

4.了解"Main"方法所做的工作。

5.学会如何读取命令行输入信息。

6.学会使用控制台输入/输出 (I/O)语句。

1.清单1-1. 一个简单的欢迎程序Welcome.cs

// Namespace Declaration
using System;
// Program start class
class WelcomeCSS {
// Main begins program execution.
public static void Main() {
// Write to console
Console.WriteLine("Welcome to the C# Station Tutorial!");
}
}

说明


1.清单1-1中的程序包括四个基本元素:名称空间的声明,类,"Main"方法和语句。

2.本例中对名称空间的声明,表明正在使用"System"这个名称空间。

名称空间内包含了一组可以被C#程序调用的代码。有了"using System;"这个声明,就表明程序可以引用该"System"名称空间内的代码,而无需在每个引用的前面加上"System"。关于这一点,我将在后面专门介绍名称空间的课程中详细介绍。

3.类"class WelcomeCSS"包含了程序所要用到的数据,和所要执行的方法的定义。

同诸如接口和结构这样的元素类似,类在程序中是用来描述对象的,这些元素都将会在后续课程中详细介绍。本例中的类不包含数据,只包含一个方法。该方法定义了该类的行为(或者称为该类所能做的事情)。

4.程序运行时,WelcomeCSS类中的该方法表明了该类所要完成的事情。

方法名"Main"作为保留字,作为程序的起点。"Main"前面是个名为"static"的修饰符。"static"修饰符表明该方法仅仅在该特定的类中工作,而不是在在该类的实例中工作。这是必需的,因为一旦程序启动后,并不存在对象的实例。类,对象和实例的具体用法将会在后面的课程中覆盖到。每个方法必须有个返回值类型。本例中,返回值类型是"void",它表明"Main"函数没有返回值。每个方法名的后面也都跟着个参数表,参数表包含有零个或者多个参数并用括号括起来。为了简单起见,没有在"Main"后面添加参数。后面的课程中,将介绍"Main"方法所允许采用的参数类型。

5."Main"方法通过"Console.WriteLine(...)" 语句表明其行为。

"Console" 是"System" 名称空间中的类。"WriteLine(...)"是"Console" 类中的方法。我们使用"."这个句点操作符来标记程序中的从属元素。注意到,我们也可以这样来书写:"System.Console.WriteLine(...)",这样的书写格式是很有趣的,它是根据"namespace.class.method" 的格式进行书写的。如果在程序的一开始,没有采用"using System"的声明,那么就必须严格遵守"System.Console.WriteLine(...)"这样的书写格式。该语句的执行结果是在控制台控制台上输出字符串"Welcome to the C# Station Tutorial!" 。

6.注释是由"//"标出的。

例子中的这些注释都是单行注释,表明从该注释符号的开始处到该行结束处,都是注释部分。如果你的注释要跨越若干行,即多行注释,可以以符号"/*"开始,以符号"*/"结束,其中所包含的全部是注释。你也可以在多行注释符号中包含单行注释。但是,不能在单行注释符号后面放上多行注释符号。程序编译时,将忽略掉注释部分。注释的目的是为了用简单的英语给程序所要完成的工作加上注解。

7.所有语句都以分号";"结束。

类和方法以"{"开始,以"}"结束。任何位于"{"和"}"之间的语句定义为块。块定义了程序元素的活动范围 (或者称为生命期和可见性),这些概念将在后面的课程中加以介绍。

8.可以编写出能够接受命令行输入信息的程序。

命令行输入信息的集合是在"Main"方法中进行处理的。清单1-2中的程序,可以从命令行中接受输入一个名字,之后在控制台上显示出来。

2.清单1-2. 读取命令行输入信息的程序NamedWelcome.cs

// Namespace Declaration
using System;
// Program start class
class NamedWelcome {
// Main begins program execution.
public static void Main(string[] args) {
// Write to console
Console.WriteLine("Hello, {0}!", args[0]);
Console.WriteLine("Welcome to the C# Station Tutorial!");
}
}

说明


1.记住,要把你的名字添加到命令行中。

例如,在命令行中打入"NamedWelcome Joe"。如果不这样做,程序就会崩溃,在后面的课程中,将介绍如何检测这种情况,以及如何避免这种情况的出现。

2.在清单1-2中,在"Main"方法的参数表中有个入口。

参数名是"args"。 在程序的后面部分就要引用该参数。"string[]"是参数"args"的类型。"string"类型用于存放字符。这些字符可以是一个单词,也可以是多个单词。方括号"[]"表示数组,"args"参数由命令行上的若干个单词构成。

3.在"Main"方法的语句中,多了一条"Console.WriteLine(...)"语句。

该语句中的参数表同以往的写法不同,其中有个格式字符串"{0}" 参数。 格式串中的第一个参数从数字0开始,第二个参数从数字1开始,依此类推。 "{0}" 参数意味着引号后面的参数值将会输出到该位置。现在让我们来看看引号后面的参数。

4."args[0]"参数,它指向"args"数组中的第一个字符串。

数组中的第一个元素是args[0], 第二个元素是args[1],依此类推。例如,如果我在命令行中写上"NamedWelcome Joe","args[0]"的值就为"Joe".

 

让我们回到在格式字符串中嵌入的"{0}" 参数吧,因为"args[0]"是格式串后面的第一个参数, 一旦执行该命令时,"args[0]"的值"Joe"就会替换掉格式串中的"{0}"。一旦执行命令:"NamedWelcome Joe",输出结果就会为:

>Hello, Joe!
>Welcome to the C# Station Tutorial!

通过控制台也可以把输入信息提供给程序。清单1-3演示了交互式处理用户输入的信息的方法。

3.清单1-3. 交互式处理输入信息的程序 InteractiveWelcome.cs

// Namespace Declaration
using System;
// Program start class
class NamedWelcome {
// Main begins program execution.
public static void Main() {
// Write to console/get input
Console.Write("What is your name?: ");
Console.Write("Hello, {0}! ", Console.ReadLine());
Console.WriteLine("Welcome to the C# Station Tutorial!");
}
}

说明

这一次,"Main"方法没有用到任何参数,但现在程序中有了三条语句,前面两条语句不同于第三条语句,它们是:"Console.Write(...)"而不是 "Console.WriteLine(...)"。区别是:"Console.Write(...)"语句把信息输出到控制台,之后光标停留在同一行,而"Console.WriteLine(...)"把信息输出,之后换行。

第一条语句仅仅输出"What is your name?: "到控制台。

第二条语句要等到其参数被适当地处理之后,才会输出信息。 格式串后面的第一个参数是:"Console.ReadLine()"。这就使得程序要等待用户在控制台输入信息,输入信息以回车或者换行结束。该方法的返回值替换了格式串中的"{0}"参数,并输出到控制台上。

最后一个语句也用来输出信息到控制台,这一点我们在前面已经介绍过。一旦运行了程序"InteractiveWelcome",其输出结果为:

>What is your Name?
>Hello, ! Welcome to the C# Station Tutorial!

小结
到现在为止,你已经了解了C#程序的基本结构,名称空间和类。你还了解到"Main"方法是C# 程序的入口,并学会了如何捕捉命令行的输入信息,以及如何进行交互式的I/O操作。大家继续学吧..教程会继续放出来的..我先看家有喜事2009 电影去了....

 

posted @ 2009-01-15 06:24 枫子52011 阅读(98) 评论(0) 编辑
posted @ 2008-12-20 00:50 枫子52011 阅读(170) 评论(0) 编辑
posted @ 2008-12-20 00:48 枫子52011 阅读(228) 评论(1) 编辑
posted @ 2008-12-20 00:47 枫子52011 阅读(795) 评论(0) 编辑