标题: 请教正则表达式 [打印本页] 作者: shiyiming 时间: 2009-12-20 14:57 标题: 请教正则表达式 data old;
input name $60.;
datalines;
Judith S Reaveley
Ralph F. Morgan
Jess Ennis
Carol Echols
Kelly Hansen Huff
Judith
Nick
Jones
;
data new;
length first middle last $ 40;
re1 = prxparse('/(\S+)\s+([^\s]+\s+)?(\S+)/o');
re2 = prxparse('/(\S+)\(s+)([^\s]+\s+)(?)(\S+)/o');
set old;
id=prxmatch(re1, name);
if id then
do;
first = prxposn(re1, 1, name);
middle = prxposn(re1, 2, name);
last = prxposn(re1, 3, name);
end;
test = prxposn(re2, 4, name);
run;
问题2:/*2.在re1定义中,为什么有的加括号,如\S+,有的又不加,如\s+?加括号和不加括号有什么不一样呢?*/
(pattern) matches a pattern and creates a capture buffer for the match. To retrieve the position and length of the match that is captured, use CALL PRXPOSN. To retrieve the value of the capture buffer, use the PRXPOSN function. To match parentheses characters,use [color=#FF0000:3hncmk3j] "\(" or "\)". [/color:3hncmk3j]
问题3:/*3.斜杠最后的那个o是什么意思?查help没有查到。*/
If perl-regular-expression is a constant or if it uses the /o option, then the Perl regular expression is compiled once and each use of PRXCHANGE reuses the compiled expression. If perl-regular-expression is not a constant and if it does not use the /o option, then the Perl regular expression is recompiled for each call to PRXCHANGE.
问题4:/*4.prxposn函数第二个参数叫capture-buffer,翻译成中文是什么意思呢?*/
我觉得可以翻译成:匹配器/俘获器?(胡乱译的,不要当真。)主要是它的原义,可见问题2的解答:“matches a pattern and creates a capture buffer for the match”。作者: shiyiming 时间: 2009-12-21 20:11 标题: Re: 请教正则表达式 多谢大侠如此细致的回复。不过我对于第二个问题还是有点疑问,为什么原来的正则表达式中的1;3;5位置上使用了括号,而2;4位置上只是用\s+和?来表示?我说的意思不是你回答的只有左括号或右括号的问题。多谢了!作者: shiyiming 时间: 2009-12-22 09:02 标题: Re: 请教正则表达式 我也不知道哦,其实我对Perl也不熟,因为你的问题才看了看SAS的help文档。
我把我自己的理解写在下面([color=#FF8000:39gp6z7m]非官方解释,不要当真[/color:39gp6z7m]。期待高手解答):
括号的作用就是为了matches a pattern and creates a capture buffer for the match.也就是说加在括号里的字符必须符合perl语句的要求,例如re1 = prxparse('/(\S+)\s+([^\s]+\s+)?(\S+)/o');
[color=#FF0000:39gp6z7m]第一部分[/color:39gp6z7m]:“(\S+)”:我们把“\S”和“+”独立出来看(在SAS Functions and CALL Routines 中的Pattern Matching Using SAS Regular Expressions (RX) and Perl Regular Expressions (PRX)页面下有关于这两个对应字符的解释,我也说不清楚,你自己找出来看看。),然后匹配你的示例数据“Judith S Reaveley”的第一个词“Judith”。
[color=#FF0000:39gp6z7m]第二部分[/color:39gp6z7m]“\s+”:和第一部分同理分解看SAS的help解说。然后匹配的示例数据“Judith S Reaveley”的第二部分字符“ ”。(什么都没有,对了,就是一个空格。)
[color=#FF0000:39gp6z7m]第三部分[/color:39gp6z7m]“([^\s]+\s+)”。。。
最后:
first = prxposn(re1, [color=#FF0000:39gp6z7m]1[/color:39gp6z7m], name);
middle = prxposn(re1, [color=#FF0000:39gp6z7m]2[/color:39gp6z7m], name);
last = prxposn(re1, [color=#FF0000:39gp6z7m]3[/color:39gp6z7m], name);
data b;
set test;
if _n_=1 then re=PRXPARSE("/(\w+),(\w+)/");
retain re;
id=prxmatch(re,x);
if id then do;
r1=PRXPOSN(re,1,x);
r2=PRXPOSN(re,2,x);
end;
run;