这是一个软件 PERL语言的接口,有可能把它改成VB接口

ok48 2011-01-13 10:16:57
这是一个软件 PERL语言的接口,有可能把它改成VB接口么???









=head
Package for running Perl programs in a Genesis environment.

This file is included by Genesis.pm.
See Genesis.pm for general documentation.

=cut
require 5.003;
require Exporter;
require 'shellwords.pl';
my $version = '2.0';

use Socket;
@ISA = qw(Exporter);


$socketOpen = 0 ;
$DIR_PREFIX = '@%#%@' ;

END {
if ($socketOpen == 0 ) {
return ;
}
send(SOCK, "${DIR_PREFIX}CLOSEDOWN \n", 0);
close (SOCK) || warn "close: $!";
}

sub new {
local $class = shift; # name
local $remote = shift;
local $genesis;

$remote = 'localhost' unless defined $remote;

# If standard input is not a terminal then we are a pipe to csh, and hence
# presumably running under Genesis. In this case use stdin and stdout as is.
# If, on the other hand, stdin is a tty, then we are running remotely, in which case
# set up the communications, namely the socket, so that we communicate.

$genesis->{remote} = $remote;
$genesis->{port} = 'genesis';

bless $genesis, $class;

$genesis->{comms} = 'pipe';
if (-t STDIN) {
$genesis->{comms} = 'socket';
$genesis->openSocket();
$genesis->{socketOpen} = 1;
$genesis->inheritEnvironment();
}
binmode(STDOUT);
return $genesis;
}
sub closeDown {
local ($genesis) = shift;
$genesis->sendCommand("CLOSEDOWN","");
}

sub inheritEnvironment {
local ($genesis) = shift;
$genesis->sendCommand("GETENVIRONMENT","");
while (1) {
$reply = $genesis->getReply();
if ($reply eq 'END') {
last;
}
($var,$value) = split('=',$reply,2);
$ENV{$var} = $value;
}
# And here is a patch for LOCALE. IBM AIX defines LC_MESSAGES and LC__FASTMSG
# which are not right if you are running remotely
undef $ENV{LC_MESSAGES};
undef $ENV{LC__FASTMSG};
}

=head
sub DESTROY {
local ($genesis) = shift;
$socketOpen -- ; # reduce reference count
if ($socketOpen) {
return ;
}
if ($genesis->{socketOpen}) {
$genesis->closeDown() ;
close (SOCK) || warn "close: $!";;
}
}
=cut


sub openSocket {
local ($genesis) = shift;
local ($remote,$port, $iaddr, $paddr, $proto);
$socketOpen ++ ;
return if $socketOpen != 1 ;
$port = $genesis->{port} ;
$remote = $genesis->{remote};

if ($port =~ /\D/) {
$port = getservbyname($port, 'tcp');
}

if (! defined $port) {
$port = 56753;
# The port has not been defined. To define it you need to
# become root and add the following line in /etc/services
# genesis 56753/tcp # Genesis port for debugging perl scripts
}
$iaddr = inet_aton($remote) || die "no host: $remote";
$paddr = sockaddr_in($port, $iaddr);
$proto = getprotobyname('tcp');
socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
connect(SOCK, $paddr) || die "connect: $!";
}



# remove excess white space
sub removeNewlines {
local($command) = shift;
$command =~ s/\n\s*/ /g;
return $command;
}

# send the command to be executed
sub sendCommand {
local($genesis) = shift;
local $commandType = shift;
local $command = shift;

$genesis->blankStatusResults();
if ($genesis->{comms} eq 'pipe') {
$genesis->sendCommandToPipe($commandType,$command);
} elsif ($genesis->{comms} eq 'socket') {
$genesis->sendCommandToSocket($commandType,$command);
}
}

sub sendCommandToPipe {
local($genesis) = shift;
local $commandType = shift;
local $command = shift;
local $old_select = select (STDOUT);
local $flush_status = $|; # save the flushing status
$| = 1; # force flushing of the io buffer
print $DIR_PREFIX, "$commandType $command\n";
$| = $flush_status; # restore the original flush status
select ($old_select);
}

sub sendCommandToSocket {
local($genesis) = shift;
local $commandType = shift;
local $command = shift;
send(SOCK, "${DIR_PREFIX}$commandType $command\n", 0);
# should check for errors here !!!
}

# wait for the reply
sub getReply {
local $reply;
if ($genesis->{comms} eq 'pipe') {
chomp ($reply = <STDIN>); # chop new line character
} elsif ($genesis->{comms} eq 'socket') {
chomp ($reply = <SOCK>); # chop new line character
}
return $reply;
}

# Checking is on. If a command fails, the script fail
sub VON {
local ($genesis) = shift;
$genesis->sendCommand("VON", "");
}


# Checking is off. If a command fails, the script continues
sub VOF {
local ($genesis) = shift;
$genesis->sendCommand("VOF", "");
}


# Allow Genesis privileged activities. Normally this is executed at the
# start of each script.
sub SU_ON {
local ($genesis) = shift;
$genesis->sendCommand("SU_ON", "");
}

sub SU_OFF {
local ($genesis) = shift;
$genesis->sendCommand("SU_OFF", "");
}
sub blankStatusResults {
local ($genesis) = shift;
undef $genesis->{STATUS};
undef $genesis->{READANS};
undef $genesis->{PAUSANS};
undef $genesis->{MOUSEANS};
undef $genesis->{COMANS};
}

# Wait for a reply from a popup
sub PAUSE {
local ($genesis) = shift;
local ($command) = @_;
$genesis->sendCommand("PAUSE", removeNewlines($command));
$genesis->{STATUS} = getReply();
$genesis->{READANS} = getReply();
$genesis->{PAUSANS} = getReply();
}

# Get the mouse position
sub MOUSE {
local ($genesis) = shift;
local ($command) = @_;
$genesis->sendCommand("MOUSE", removeNewlines($command));
$genesis->{STATUS} = getReply();
$genesis->{READANS} = getReply();
$genesis->{MOUSEANS} = getReply();
}

# Send a command
sub COM {
local ($genesis) = shift;
local $command;
if (@_ == 1) {
($command) = @_;
$genesis->sendCommand("COM",removeNewlines($command));
} else {
$command = shift;
local %args = @_;
foreach (keys %args) {
$command .= ",$_=$args{$_}";
}
$genesis->sendCommand("COM", $command);
}
$genesis->{STATUS} = getReply();
$genesis->{READANS} = getReply();
$genesis->{COMANS} = $genesis->{READANS};
}

# Send an auxiliary command
sub AUX {
local ($genesis) = shift;
local $command;
if (@_ == 1) {
($command) = @_;
$genesis->sendCommand("AUX", removeNewlines($command));
} else {
$command = shift;
local %args = @_;
foreach (keys %args) {
$command .= ",$_=$args{$_}";
}
$genesis->sendCommand("AUX", $command);
}
$genesis->{STATUS} = getReply();
$genesis->{READANS} = getReply();
$genesis->{COMANS} = $genesis->{READANS};
}

# Get some basic info
# It is received in the form of a csh script, so the information needs
# hacking to get into a form suitable for perl

sub DO_INFO {
local ($genesis) = shift;
local $info_pre = "info,out_file=\$csh_file,write_mode=replace,args=";
local $info_com = "$info_pre @_ -m SCRIPT";
$genesis->parse($info_com);
}


sub parse {
local ($genesis) = shift;
local($request) = shift;
local $csh_file = "$ENV{GENESIS_DIR}/share/tmp/info_csh.$$";
$request =~ s/\$csh_file/$csh_file/;

$genesis->COM ($request);

open (CSH_FILE, "$csh_file") or warn "Cannot open info file - $csh_file: $!\n";
while (<CSH_FILE>) {
chomp;
next if /^\s*$/; # ignore blank lines
($var,$value) = /set\s+(\S+)\s*=\s*(.*)\s*/; # extract the name and value

$value =~ s/^\s*|\s*$//g; # remove leading and trailing spaces from the value
$value =~ s/\cM/<^M>/g; # change ^M temporarily to something else
# This happens mainly in giSEP, and shellwords makes it disappear

@value = shellwords($_);

# Deal with an csh array differently from a csh scalar
if ($value =~ /^\(/ ) {
$value =~ s/^\(|\)$//g; # remove leading and trailing () from the value
@words = shellwords($value); # This is a standard part of the Perl library
grep {s/\Q<^M>/\cM/g} @words;
$genesis->{doinfo}{$var} = [@words];
} else {
$value =~ s/\Q<^M>/\cM/g;
$value =~ s/^'|'$//g;
$genesis->{doinfo}{$var} = $value;
}
}
close (CSH_FILE);
unlink ($csh_file);
}

sub INFO {
local ($genesis) = shift;
local %args = @_;
local ($entity_path, $data_type, $parameters,
$serial_number, $options, $help, $entity_type, $units) = ("","","","","","","","");
local $i;
foreach (keys %args) {
$i = $args{$_};
if ($_ eq "entity_type") {
$entity_type = "-t $i";
} elsif ($_ eq "entity_path") {
$entity_path = "-e $i";
} elsif ($_ eq "data_type") {
$data_type = "-d $i";
} elsif ($_ eq "parameters") {
$parameters = "-p $i";
} elsif ($_ eq "serial_number") {
$serial_number = "-s $i";
} elsif ($_ eq "options") {
$options = "-o $i";
} elsif ($_ eq "help") {
$help = "-help";
} elsif ($_ eq "units") {
$units = "units=$i,";
}
}

local $info_pre = "info,out_file=\$csh_file,write_mode=replace,${units}args=";
local $info_com = "$info_pre $entity_type $entity_path $data_type "
. "$parameters $serial_number $options $help";

$genesis->parse($info_com);
}


sub clearDoinfo {
local ($me) = shift;
undef $me->{doinfo};
}


1;
...全文
162 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ok48 2011-01-13
  • 打赏
  • 举报
回复
Genesis.pm 文件


=head
Package for running Perl programs in a Genesis/Enterprise environment.

Usage
use Genesis;
use Genesis('122.12.1.87');
$f = new Genesis;

$f->COM($command);

This module enables Genesis/Enterprise scripts in perl.
It also supports debugging from an xterm, or remote terminal. When running the perl
script from inside Genesis, simply choose the relevant script from the
"Script Run" screen.

To run or debugging a script from an xterm, go the "Script Run" screen,
and choose the script called server.pl. This script sets up a socket which waits
for commands from the perl script to be debugged.
Having started the script server.pl, open up an xterm and start debugging the script.

The conventions in the Perl script are slightly different from the csh equivalent.

The start of the each perl script must begin with

use Genesis;

To access this library do *one* of the following:
The options appear in the order of recommendation.

* Copy Genesis.pm into the normal Perl library
* Add the path of Genesis.pm to PERL5LIB
* Type "use lib qw(/pathname)" -- where /pathname must be the directory where the file
Genesis.pm resides -- in each of your genesis scripts.
The line 'use lib' must appear before the line 'use Genesis'.

The next line should be

$f = new Genesis;

$f is simply a variable that you can choose.

The public functions are:
VON, VOF, SU_ON, SU_OFF, PAUSE, MOUSE, COM, AUX, DO_INFO, and INFO

They are invoked in the object oriented way. Here is an example of the PAUSE command
$f->PAUSE($text);

Now let's deal with variables created when using DO_INFO.
Unlike the csh, the variables are put into the the structure
pointed to by $f.

A call to "DOINFO" which reutnrs a value of "gEXISTS" would be referenced as
$f->{doinfo}{gEXISTS}. If an array were to be received, the elements could be referenced as
$f->{doinfo}{gWIDTHS}[$i].

Similary, the return results are called STATUS, READANS, PAUSANS, MOUSEANS and COMANS.
For the meantime these can be read using $f->{STATUS} etc.

BUGS

1. In debug mode: If the Abort button is pressed in Pause, the script does not terminate.

2. Every time an external script is started the Apply button has to be pressed to
restart the server side.

3. During debugging of the Perl script the Genesis editor is not updated.

Split into two files & revamped: 3 July 1997, Ben Michelson
Hacked out of all reconition, Peter Gordon
Original Version: 8 Nov 1996, Herzl Rejwan
=cut
package Genesis;

if (defined $ENV{GENESIS_DIR}) {
$_genesis_root = $ENV{GENESIS_DIR};
} else {
$_genesis_root = "/genesis";
}

if (defined $ENV{GENESIS_EDIR}) {
$_genesis_edir = $ENV{GENESIS_EDIR};
} else {
$_genesis_edir = "e$ENV{GENESIS_VER}";
}

if ($_genesis_edir !~ m#^([A-Z]:)?[/\\]#i) {
$_genesis_edir = "$_genesis_root/$_genesis_edir";
}

require "$_genesis_edir/all/perl/Genesis.pl";
"^The": 匹配以 "The"开头的字符串; "of despair$": 匹配以 "of despair" 结尾的字符串; "^abc$": 匹配以abc开头和以abc结尾的字符串,实际上是只有abc与之匹配 "notice": 匹配包含notice的字符串 你可以看见如果你没有用我们提到的两个字符(最后一个例子),就是说 模式(正则表达式) 可以出现在被检验字符串的任何地方,你没有把他锁定到两边 这里还有几个字符 '*', '+',和 '?', 他们用来表示一个字符可以出现的次数或者顺序. 他们分别表示:"zero or more", "one or more", and "zero or one." 这里是一些例子: "ab*": 匹配字符串a和0个或者更多b组成的字符串("a", "ab", "abbb", etc.); "ab+": 和上面一样,但最少有一个b ("ab", "abbb", etc.); "ab?":匹配0个或者一个b; "a?b+$": 匹配以一个或者0个a再加上一个以上的b结尾的字符串. 你也可以在大括号里面限制字符出现的个数,比如 "ab{2}": 匹配一个a后面跟两个b(一个也不能少)("abb"); "ab{2,}": 最少更两个b("abb", "abbbb", etc.); "ab{3,5}": 2-5个b("abbb", "abbbb", or "abbbbb"). 你还要注意到你必须总是指定 (i.e, "{0,2}", not "{,2}").同样,你必须注意到, '*', '+', 和'?' 分别和一下三个范围标注是一样的,"{0,}", "{1,}", 和 "{0,1}"。 现在把一定数量的字符放到小括号里,比如: "a(bc)*": 匹配 a 后面跟0个或者一个"bc"; "a(bc){1,5}": 一个到5个 "bc." 还有一个字符 '│', 相当于OR 操作: "hi│hello": 匹配含有"hi" 或者 "hello" 的 字符串; "(b│cd)ef": 匹配含有 "bef" 或者 "cdef"的字符串; "(a│b)*c": 匹配含有这样 - 多个(包括0个)a或b,后面跟一个c 的字符串 的字符串; 一个点('.')可以代表所有的 单一字符: "a.[0-9]": 一个a跟一个字符再跟一个数字的 (含有这样一个字符串的字符串将被匹配,以后省略此括号) "^.{3}$": 以三个字符结尾 . 中括号括住的内容只匹配一个 单一的字符 "[ab]": 匹配单个的 a 或者 b ( 和 "a│b" 一样); "[a-d]": 匹配'a' 到'd'的单个字符 (和"a│b│c│d" 还有 "[abcd]"效果一样); "^[a-zA-Z]": 匹配以字母开头的字符串 "[0-9]%": 匹配含有 形如 x% 的字符串 ",[a-zA-Z0-9]$": 匹配以逗号在加一个数字或字母结尾的字符串 你也可以把你不想要得字符列在中括号里,你只需要在总括号里面使用'^' 作为开头 (i.e., "%[^a-zA-Z]%" 匹配含有 两个百分号里面有一个非字母 的字符串). 为了能够解释,但"^.[$()│*+?{\"作为有特殊意义的字符的时候,你必须在这些字符面前加'', 还有在php3中你应该避免在模式的最前面使用\, 比如说,正则表达式 "(\$│?[0-9]+" 应该这样调用 ereg("(\\$│?[0-9]+", $str) (不知道php4是不是一样) 不要忘记在中括号里面的字符是这条规路的例外—在中括号里面, 所有的特殊字符,包括(''), 都将失去他们的特殊性质(i.e., "[*\+?{}.]"匹配含有这些字符的字符串). 还有,正如regx的手册告诉我们: "如果列表里含有 ']', 最好把它作为列表里的第一个字符(可能跟在'^'后面). 如果含有'-', 最好把它放在最前面或者最后面, or 或者一个范围的第二个结束点(i.e. [a-d-0-9]中间的‘-’将有效. 为了完整, 我应该涉及到 collating sequences, character classes, 同埋 equivalence classes. 但我在这些方面不想讲的太详细, 这些在下面的文章仲都不需要涉及到. 你们可以在regex man pages 那里得到更多消息. 如何构建一个模式来匹配 货币数量 的输入 好了,现在我们要用我们所学的来干一些有用的事:构建一个匹配模式去检查输入的信息是否为一个表示money的数字。我们认为一个表示money的数量有四种方式: "10000.00" 和 "10,000.00",或者没有小数部分, "10000" and "10,000". 现在让我们开始构建这个匹配模式: ^[1-9][0-9]*$ 这是所变量必须以非0的数字开头.但这也意味着 单一的 "0" 也不能通过测试. 以下是解决的方法: ^(0│[1-9][0-9]*)$ "只有0和不以0开头的数字与之匹配",我们也可以允许一个负号再数字之前: ^(0│-?[1-9][0-9]*)$ 这就是: "0 或者 一个以0开头可能一个负号在前面的数字." 好了, 好了现在让我们别那么严谨,允许以0开头.现在让我们放弃 负号 , 因为我们在表示钱币的时候并不需要用到. 我们现在指定 模式 用来匹配小数部分: ^[0-9]+(\.[0-9]+)?$ 这暗示匹配的字符串必须最少以一个阿拉伯数字开头. 但是注意,在上面模式中 "10." 是不匹配的, 只有 "10" 和 "10.2" 才可以. (你知道为什么吗) ^[0-9]+(\.[0-9]{2})?$ 我们上面指定小数点后面必须有两位小数.如果你认为这样太苛刻,你可以改成: ^[0-9]+(\.[0-9]{1,2})?$ 这将允许小数点后面有一到两个字符. 现在我们加上用来增加可读性的逗号(每隔三位), 我们可以这样表示: ^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]{1,2})?$ 不要忘记加号 '+' 可以被乘号 '*' 替代如果你想允许空白字符串被输入话 (为什么?). 也不要忘记反斜杆 ’\’ 在php字符串中可能会出现错误 (很普遍的错误). 现在,我们已经可以确认字符串了, 我们现在把所有逗号都去掉 str_replace(",", "", $money) 然后在把类型看成 double然后我们就可以通过他做数学计算了. 构造检查email的正则表达式 好,让我们继续讨论怎么验证一个email地址. 在一个完整的email地址中有三个部分: POP3 用户名 (在 '@' 左边的一切), '@', 服务器名(就是剩下那部分). 用户名可以含有大小写字母阿拉伯数字,句号 ('.'), 减号('-'), and 下划线 ('_'). 服务器名字也是符合这个规则,当然下划线除外. 现在, 用户名的开始和结束都不能是句点. 服务器也是这样. 还有你不能有两个连续的句点他们之间至少存在一个字符,好现在我们来看一下怎么为用户名写一个匹配模式: ^[_a-zA-Z0-9-]+$ 现在还不能允许句号的存在. 我们把它加上: ^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*$ 上面的意思就是说: "以至少一个规范字符(除.意外)开头,后面跟着0个或者多个以点开始的字符串." 简单化一点, 我们可以用 eregi()取代 ereg().eregi()对大小写不敏感, 我们就不需要指定两个范围 "a-z" 和 "A-Z" – 只需要指定一个就可以了: ^[_a-z0-9-]+(\.[_a-z0-9-]+)*$ 后面的服务器名字也是一样,但要去掉下划线: ^[a-z0-9-]+(\.[a-z0-9-]+)*$ Done. 现在只需要用”@”把两部分连接: ^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$ 这就是完整的email认证匹配模式了,只需要调用 eregi(‘^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$ ’,$eamil) 就可以得到是否为email了 正则表达式的其他用法 提取字符串 ereg() and eregi() 有一个特性是允许用户通过正则表达式去提取字符串的一部分(具体用法你可以阅读手册). 比如说,我们想从 path/URL 提取文件名 – 下面的代码就是你需要: ereg("([^\\/]*)$", $pathOrUrl, $regs); echo $regs[1]; 高级的代换 ereg_replace() 和 eregi_replace()也是非常有用的: 假如我们想把所有的间隔负号都替换成逗号: ereg_replace("[ \n\r\t]+", ",", trim($str)); PHP被大量的应用于Web的后台CGI开发,通常是在用户数据数据之后得出某种结果,但是如果用户输入的数据不正确,就会出现问题,比如说某人的生日是"2月30日"!那应该怎么样来检验暑假是否正确呢? 在PHP中加入了正则表达式的支持,让我们可以十分方便的进行数据匹配。 2 什么是正则表达式: 简单的说,正则表达式是一种可以用于模式匹配和替换的强大工具。在几乎所有的基于UNIX/LINUX系统的软件工具中找到正则表达式的痕迹,例如:Perl或PHP脚本语言。此外,JavaScript这种客户端的脚本语言也提供了对正则表达式的支持,现在正则表达式已经成为了一个通用的概念和工具,被各类技术人员所广泛使用。 在某个Linux网站上面有这样的话:"如果你问一下Linux爱好者最喜欢什么,他可能会回答正则表达式;如果你问他最害怕什么,除了繁琐的安装配置外他肯定会说正则表达式。" 正如上面说的,正则表达式看起来非常复杂,让人害怕,大多数的PHP初学者都会跳过这里,继续下面的学习,但是PHP中的正则表达式有着可以利用模式匹配找到符合条件的字符串、判断字符串是否合乎条件或者用指定的字符串来替代符合条件的字符串等强大的功能,不学实在太可惜了…… 3 正则表达式的基本语法: 一个正则表达式,分为三个部分:分隔符,表达式和修饰符。 分隔符可以是除了特殊字符以外的任何字符(比如"/ !"等等),常用的分隔符是"/"。表达式由一些特殊字符(特殊字符详见下面)和非特殊的字符串组成,比如"[a-z0-9_-]+@[a-z0-9_-.]+"可以匹配一个简单的电子邮件字符串。修饰符是用来开启或者关闭某种功能/模式。下面就是一个完整的正则表达式的例子: /hello.+?hello/is 上面的正则表达式"/"就是分隔符,两个"/"之间的就是表达式,第二个"/"后面的字符串"is"就是修饰符。 在表达式中如果含有分隔符,那么就需要使用转义符号"\",比如"/hello.+?\/hello/is"。转义符号除了用于分隔符外还可以执行特殊字符,全部由字母构成的特殊字符都需要"\"来转义,比如"\d"代表全体数字。 4 正则表达式的特殊字符: 正则表达式中的特殊字符分为元字符、定位字符等等。 元字符是正则表达式中一类有特殊意义的字符,用来描述其前导字符(即元字符前面的字符)在被匹配的对象中出现的方式。元字符本身是一个个单一的字符,但是不同或者相同的元字符组合起来可以构成大的元字符。 元字符: 大括号:大括号用来精确指定匹配元字符出现的次数,例如"/pre{1,5}/"表示匹配的对象可以是"pre"、"pree"、"preeeee"这样在"pr"后面出现1个到5个"e"的字符串。或者"/pre{,5}/"代表pre出现0此到5次之间。 加号:"+"字符用来匹配元字符前的字符出现一次或者多次。例如"/ac+/"表示被匹配的对象可以是"act"、"account"、"acccc"等在"a"后面出现一个或者多个"c"的字符串。"+"相当于"{1,}"。 星号:"*"字符用来匹配元字符前的字符出现零次或者多次。例如"/ac*/"表示被匹配的对象可以是"app"、"acp"、"accp"等在"a"后面出现零个或者多个"c"的字符串。"*"相当于"{0,}"。 问号:"?"字符用来匹配元字符前的字符出现零次或者1次。例如"/ac?/"表示匹配的对象可以是"a"、"acp"、"acwp"这样在"a"后面出现零个或者1个"c"的字符串。"?"在正则表达式中还有一个非常重要的作用,即"贪婪模式"。 还有两个很重要的特殊字符就是"[ ]"。他们可以匹配"[]"之中出现过的字符,比如"/[az]/"可以匹配单个字符"a"或者"z";如果把上面的表达式改成这样"/[a-z]/",就可以匹配任何单个小写字母,比如"a"、"b"等等。 如果在"[]"中出现了"^",代表本表达式不匹配"[]"内出现的字符,比如"/[^a-z]/"不匹配任何小写字母!并且正则表达式给出了几种"[]"的默认值: [:alpha:]:匹配任何字母 [:alnum:]:匹配任何字母和数字 [:digit:]:匹配任何数字 [:space:]:匹配空格符 [:upper:]:匹配任何大写字母 [:lower:]:匹配任何小写字母 [:punct:]:匹配任何标点符号 [:xdigit:]:匹配任何16进制数字 另外下面这些特殊字符在转义符号"\"转义后代表的含义如下: s:匹配单个的空格符 S:用于匹配除单个空格符之外的所有字符。 d:用于匹配从0到9的数字,相当于"/[0-9]/"。 w:用于匹配字母,数字或下划线字符,相当于"/[a-zA-Z0-9_]/"。 W:用于匹配所有与w不匹配的字符,相当于"/[^a-zA-Z0-9_]/"。 D:用于匹配任何非10进制的数字字符。 .:用于匹配除换行符之外的所有字符,如果经过修饰符"s"的修饰,"."可以代表任意字符。 利用上面的特殊字符可以很方便的表达一些比较繁琐的模式匹配。例如"/\d0000/"利用上面的正则表达式可以匹配万以上,十万一下的整数字符串。 定位字符: 定位字符是正则表达式中又一类非常重要的字符,它的主要作用是用于对字符在匹配对象中的位置进行描述。 ^:表示匹配的模式出现在匹配对象的开头(和在"[]"里面不同) $:表示匹配的模式出现在匹配对象的末尾 空格:表示匹配的模式出现在开始和结尾的两个边界之一 "/^he/":可以匹配以"he"字符开头的字符串,比如hello、height等等; "/he$/":可以匹配以"he"字符结尾的字符串即she等; "/ he/":空格开头,和^的作用一样,匹配以he开头的字符串; "/he /":空格结束,和$的作用一样,匹配以he结尾的字符串; "/^he$/":表示只和字符串"he"匹配。 括号: 正则表达式除了可以用户匹配,还可以用括号"()"来记录需要的信息,储存起来,给后面的表达式读取。比如: /^([a-zA-Z0-9_-]+)@([a-zA-Z0-9_-]+)(.[a-zA-Z0-9_-])$/ 就是记录邮件地址的用户名,和邮件地址的服务器地址(形式为username@server.com之类的),在后面如果想要读取记录下来的字符串,只是需要用"转义符+记录的次序"来读取。比如"\1"就相当于第一个"[a-zA-Z0-9_-]+","\2"相当于第二个([a-zA-Z0-9_-]+),"\3"就是第三个(.[a-zA-Z0-9_-])。但是在PHP中,"\"是一个特殊的字符,需要转义,所以""到了PHP的表达式中就应该写成"\\1"。 其他特殊符号: "|":或符号"|"和PHP里面的或一样,不过是一个"|",而不是PHP的两个"||"!意思就是可以是某个字符或者另一个字符串,比如"/abcd|dcba/"可能匹配"abcd"或者"dcba"。 5 贪婪模式: 前面在元字符中提到过"?"还有一个重要的作用,即"贪婪模式",什么是"贪婪模式"呢? 比如我们要匹配以字母"a"开头字母"b"结尾的字符串,但是需要匹配的字符串在"a"后面含有很多个"b",比如"a bbbbbbbbbbbbbbbbb",那正则表达式是会匹配第一个"b"还是最后一个"b"呢?如果你使用了贪婪模式,那么会匹配到最后一个"b",反之只是匹配到第一个"b"。 使用贪婪模式的表达式如下: /a.+?b/ /a.+b/U 不使用贪婪模式的如下: /a.+b/ 上面使用了一个修饰符U,详见下面的部分。 6 修饰符: 在正则表达式里面的修饰符可以改变正则的很多特性,使得正则表达式更加适合你的需要(注意:修饰符对于大小写是敏感的,这意味着"e"并不等于"E")。正则表达式里面的修饰符如下: i :如果在修饰符中加上"i",则正则将会取消大小写敏感性,即"a"和"A" 是一样的。 m:默认的正则开始"^"和结束"$"只是对于正则字符串如果在修饰符中加上"m",那么开始和结束将会指字符串的每一行:每一行的开头就是"^",结尾就是"$"。 s:如果在修饰符中加入"s",那么默认的"."代表除了换行符以外的任何字符将会变成任意字符,也就是包括换行符! x:如果加上该修饰符,表达式中的空白字符将会被忽略,除非它已经被转义。 e:本修饰符仅仅对于replacement有用,代表在replacement中作为PHP代码。 A:如果使用这个修饰符,那么表达式必须是匹配的字符串中的开头部分。比如说"/a/A"匹配"abcd"。 E:与"m"相反,如果使用这个修饰符,那么"$"将匹配绝对字符串的结尾,而不是换行符前面,默认就打开了这个模式。 U:和问号的作用差不多,用于设置"贪婪模式"。 7 PCRE相关的正则表达式函数: PHP的Perl兼容正则表达式提供的多个函数,分为模式匹配,替换和匹配数目等等: 1、preg_match : 函数格式:int preg_match(string pattern, string subject, array [matches]); 这个函数会在string中使用pattern表达式来匹配,如果给定了[regs],就会将string记录到[regs][0]中,[regs][1]代表使用括号"()"记录下来的第一个字符串,[regs][2]代表记录下来的第二个字符串,以此类推。preg如果在string中找到了匹配的pattern,就会返回"true",否则返回"false"。 2、preg_replace : 函数格式:mixed preg_replace(mixed pattern, mixed replacement, mixed subject); 这个函数会使用将string中符合表达式pattern的字符串全部替换为表达式replacement。如果replacement中需要包含pattern的部分字符,则可以使用"()"来记录,在replacement中只是需要用"\1"来读取。 3、preg_split : 函数格式:array preg_split(string pattern, string subject, int [limit]); 这个函数和函数split一样,区别仅在与split可以使用简单正则表达式来分割匹配的字符串,而preg_split使用完全的Perl兼容正则表达式。第三个参数limit代表允许返回多少个符合条件的值。 4、preg_grep : 函数格式:array preg_grep(string patern , array input); 这个函数和preg_match功能基本上,不过preg_grep可以将给定的数组input中的所有元素匹配,返回一个新的数组。 下面举一个例子,比如我们要检查Email地址的格式是否正确: <?php function emailIsRight($email) { if (preg_match("^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3}$",$email)) { return 1; } return 0; } if(emailIsRight('y10k@963.net')) echo '正确
'; if(!emailIsRight('y10k@fffff')) echo '不正确
'; ?> 上面的程序会输出"正确
不正确"。 8.PHP中的Perl兼容正则表达式和Perl/Ereg正则表达式的区别: 虽然叫做“Perl兼容正则表达式”,但是和Perl的正则表达式相比,PHP的还是由一些不同,比如修饰符“G”在Perl里面代表全部匹配,但是在PHP中没有加入对这个修饰符的支持。 还有就是和ereg系列函数的区别,ereg也是PHP中提供的正则表达式函数,不过和preg相比,要弱上很多。 1、ereg里面是不需要也不能使用分隔符和修饰符的,所以ereg的功能比preg要弱上不少。 2、关于".":点在正则里面一般是除了换行符以外的全部字符,但是在ereg里面的"."是任意字符,即包括换行符!如果在preg里面希望"."能够包括换行符,可以在修饰符中加上"s"。 3、ereg默认使用贪婪模式,并且不能修改,这个给很多替换和匹配带来麻烦。 4、速度:这个或许是很多人关心的问题,会不会preg功能强大是以速度来换取的?不用担心,preg的速度要远远比ereg快,笔者做了一个程序测试: time test: PHP代码: <?php echo "Preg_replace used time:"; $start = time(); for($i=1;$i<=100000;$i++) { $str = "ssssssssssssssssssssssssssss"; preg_replace("/s/","",$str); } $ended = time()-$start; echo $ended; echo " ereg_replace used time:"; $start = time(); for($i=1;$i<=100000;$i++) { $str = "ssssssssssssssssssssssssssss"; ereg_replace("s","",$str); } $ended = time()-$start; echo $ended; echo " str_replace used time:"; $start = time(); for($i=1;$i<=100000;$i++) { $str = "sssssssssssssssssssssssssssss"; str_replace("s","",$str); } $ended = time()-$start; echo $ended; ?> 结果: Preg_replace used time:5 ereg_replace used time:15 str_replace used time:2 str_replace因为不需要匹配所以速度非常快,而preg_replace的速度比ereg_replace要快上不少。 9.关于PHP3.0对于preg的支持: 在PHP 4.0中默认加入了preg支持,但是在3.0中确没有。如果在3.0中希望使用preg函数,必须加载php3_pcre.dll文件,只要在php.ini的extension部分设置加入"extension = php3_pcre.dll"然后从新启动PHP就可以了! 其实正则表达式还常用于UbbCode的实现,很多PHP论坛都使用了这个方法(比如zForum zphp.com或者vB vbullent.com),但是具体的代码比较长。 本文来自http://blog.csdn.net/kkobebryant/archive/2005/01/25/267527.aspx

863

社区成员

发帖
与我相关
我的任务
社区描述
VB COM/DCOM/COM+
c++ 技术论坛(原bbs)
社区管理员
  • COM/DCOM/COM+社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧