Tải bản đầy đủ (.pdf) (46 trang)

OReilly VBScript In A Nutshell 2nd Edition Mar 2003 ISBN 0596004885

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (362.26 KB, 46 trang )

RegExp.GlobalProperty

DataType
Boolean

Description
Determineswhetherthesearchforapatternstringshould
matchalloccurrencesinthesearchstringorjustthefirstone.

RulesataGlance
Asearchwillattempttolocateonlythefirstoccurrenceofthe
patternstringinasearchstring;thatis,thedefaultvalueofthe
GlobalpropertyisFalse.Ifyouwanttosearchforall
occurrencesofthepatternstringinthesearchstring,youmust
settheGlobalpropertytoTrue.

ProgrammingTipsandGotchas
Ifyou'reinterestedonlyindeterminingwhetherthepattern
stringexistsinthesearchstring,there'snopointinoverriding
theGlobalproperty'sdefaultvalueofFalse.

SeeAlso
MatchesCollectionObject,MatchObject,RegExpObject


MatchesCollectionObject

Description
ThecollectionofzeroormoreMatchobjectsreturnedbythe
RegExpobject'sExecutemethod;eachMatchobjectallowsyou
toidentifyandmanipulateoneofthestringsfoundbythe


regularexpression.

Createable
No.

Returnedby
RegExp.ExecuteMethod.

Properties
TheMatchescollectionobjectsupportsthefollowingtwo
properties:
Count
DataType:Long
Indicatesthenumberofobjectsinthecollection.Avalueof
zeroindicatesthatthecollectionisempty.Thepropertyis
read-only.
Item
Syntax:Matches.Item(index)


DataType:Matchobject
ReturnsaparticularMatchobjectbasedonindex,its
ordinalpositioninthecollection.Matchesisazero-based
collection;thatis,itsfirstmemberisatordinalposition0,
whileitslastmemberisatordinalpositionMatches.Count1.

Example
SeetheexamplefortheMatchobject.

SeeAlso

MatchObject,RegExpObject,RegExp.ExecuteMethod


MatchObject

Description
AmemberoftheMatchescollectionthatisreturnedbyacallto
theRegExpobject'sExecutemethod,theMatchobject
representsasuccessfulregularexpressionmatch.

Createable
No.

Returnedby
Matches.Itemproperty.

Properties
TheMatchobjectsupportsthefollowingthreeproperties:
FirstIndex
DataType:Long
Indicatesthepositionintheoriginalsearchstringwherethe
regularexpressionmatchoccurred.Thefirstcharacterin
thesearchstringisatposition1.
Length
DataType:Long
Indicatesthenumberofcharactersinthematchfoundin
thesearchstring.Thisisalsothenumberofcharactersin


theMatchobject'sValueproperty.

Value
DataType:String
Thetextofthematchfoundinthesearchstring.

Example
SincetheRegExpobject'sExecutemethodsearchesonlya
string,theexampleprogramwritesthefilenameofeachfilein
theWindowsdirectorytoavariablenamedstrNames.Each
filenameisprecededbytwospaces.TheRegExpobject's
Executemethodisthencalledtosearchforeveryfilename
beginningwiththeletter"B"(theregularexpressionsearches
fortwospacesfollowedbya"B").TheMatchescollectionis
theniteratedsothateachfilenamecanbeextractedfrom
strNamesanddisplayedinamessagebox:
Dimfs,root,dir,fls,fl
Dimrexp
Dimmtchs,mtch
DimstrNames,strMsg
DimlStartPos
strNames=""
Setfs=CreateObject("Scripting.FileSystemObject")
Setroot=fs.Drives("C").RootFolder
Setdir=root.SubFolders("Windows")
Setfls=dir.Files
ForEachflInfls
strNames=strNames&fl.Name&""
Next
MsgBoxLen(strNames)
Setrexp=NewRegExp



rexp.Global=True
rexp.Pattern="(\s\sB)"
Setmtchs=rexp.Execute(strNames)

ForEachmtchInmtchs
lStartPos=mtch.FirstIndex+2
strMsg=strMsg&Mid(strNames,lStartPos,_
InStr(lStartPos,strNames,"")-lStartPos+1)&
Next
MsgBoxstrMsg

SeeAlso
RegExpObject


RegExpObject

Description
TheRegExpobjectprovidessupportforregularexpression
matchingfortheabilitytosearchstringsforsubstringsmatching
generalorspecificpatterns.
Inordertoconductapatternsearch,youmustfirstinstantiate
theregularexpressionobject,withcodelikethefollowing:
DimoRegExp'InstanceofRegExpobject
SetoRegExp=NewRegExp
ToconductasearchusingtheRegExpobject,dothefollowing:
Determinewhetherthesearchshouldbecase-sensitive.
Determinewhetherallinstancesorjustthefirstinstanceof
thesubstringshouldbereturned.

Supplythepatternstringthatyouwanttofind.
ProvideastringthattheRegExpobjectistosearch.
TheRegExpobjectallowsyoutosearchforasubstringthat
matchesyourpatternstringinanyofthreeways:
Youcandeterminewhetherapatternmatchisfoundinthe
string.
Youcanreturnoneoralloftheoccurrencesofthematching
substrings.Inthiscase,resultsarereturnedinMatch


objectswithintheMatchescollection.
Youcanreplaceallsubstringsmatchingthepatternstring
withanotherstring.

Properties
TheRegExpobjectsupportsthethreepropertiesshowninthe
followingtable.Eachisdocumentedindepthinitsownsection
intheLanguageReference.
Property
name

Description

Global

Indicateswhethertosearchforalloccurrencesofthepatternstringorjust
forthefirstone

IgnoreCase


Indicateswhetherthepatternsearchiscase-sensitive

Pattern

Indicatesthepatternstringtosearchfor

Methods
TheRegExpobjectsupportsthethreemethodsshowninthe
followingtable.Eachisdocumentedindepthinitsownsection
intheLanguageReference.
Method
name

Description

Execute

ReturnsaMatchescollectioncontaininginformationaboutthesubstringsina
largerstringthatmatchapatternstring

Replace

Replacesallsubstringsinalargerstringthatmatchapatternstringwitha
secondstring


Test

Indicateswhetherthesearchofastringhassucceededinfindingapattern
match


VBA/VBScriptDifferences
TheRegExpobject,whichwasintroducedtogiveVBScript
comparablefeaturestoJScript,isexclusivetoVBScript;itdoes
notexistasacorepartoftheVBAlanguage.However,the
RegExpobjectisimplementedasamemberoftheVBScript.dll
libraryandcanbeaddedtoanyVisualBasicproject.Itislisted
intheReferencesdialog(whichisavailablebyselectingthe
ReferencesoptionfromtheVisualBasicProjectmenu)as
"MicrosoftVBScriptRegularExpressions."

SeeAlso
InStr,InStrBFunctions,InstrRevFunction,MatchObject,
MatchesCollectionObject


RegExp.ExecuteMethod

Syntax
RegExp.Execute(string)
string
Use:Required
DataType:String
Thestringtobesearched.

ReturnValue
AMatchescollectioncontainingoneormoreMatchobjects.

Description
Performsaregularexpressionsearchagainststringand

returnstheresultsintheMatchescollection.

RulesataGlance
ThemethodsearchesstringusingtheRegExpobject's
Patternproperty.
TheresultsarereturnedintheMatchescollection,whichis
acollectionofMatchobjects.
Ifthesearchfindsnomatches,theMatchescollectionis
empty.


ProgrammingTipsandGotchas
RemembertousetheSetstatementtoassigntheMatches
collectionreturnedbytheExecutemethodtoanobject
variable.
YoucandeterminewhethertheMatchescollectionreturned
bytheExecutemethodisemptybyexaminingitsCount
property.ItisemptyifthevalueofCountis0.

Example
SeetheexamplefortheRegExp.PatternProperty.

SeeAlso
MatchesCollectionObject,RegExp.PatternProperty,
RegExp.ReplaceMethod,RegExp.TestMethod


InStr,InStrBFunctions

Syntax

InStr([start,]stringtosearch,stringtofind[,comparemode
start
Use:Optional
DataType:Numeric
Thestartingpositionforthesearch.
stringtosearch
Use:Required
DataType:String
Thestringbeingsearched.
stringtofind
Use:Required
DataType:String
Thestringbeingsought.
comparemode
Use:Optional
DataType:Integer
Thetypeofstringcomparison.


ReturnValue
ALong.

Description
Findsthestartingpositionofonestringwithinanother.

RulesataGlance
ThereturnvalueofInStrisinfluencedbythevaluesof
stringtosearchandstringtofind,asshowninthe
followingtable:
Condition


InStrreturnvalue

stringtosearchiszero-length

0

stringtosearchisNull

Null

stringtofindiszero-length

start

stringtofindisNull

Null

stringtofindisnotfound

0

stringtofindisfoundwithin
stringtosearch

Positionatwhichthestartofstringtofindis
found

start>len(stringtofind)


0

Ifthestartargumentisomitted,InStrcommencesthe
searchwiththefirstcharacterofstringtosearch.


IfthestartargumentisNull,anerroroccurs.
Youmustspecifyastartargumentifyouarespecifyinga
comparemodeargument.
VBScriptsupportsintrinsicconstantsforcomparemode,as
follows:
Comparisonmode

Value

Constant

Binary(default)

0

vbBinaryCompare

Textcase-insensitive

1

vbTextCompare


Ineffect,abinarycomparisonmeansthatthesearchfor
stringtofindinstringtosearchiscase-sensitive.Atext
comparisonmeansthatthesearchforstringtofindin
stringtosearchisnotcase-sensitive.
IfthecomparemodeargumentcontainsNull,anerroris
generated.
Ifcomparemodeisomitted,thetypeofcomparisonis
vbBinaryCompare.

ProgrammingTipsandGotchas
YoucanusetheInStrBfunctiontocomparebytedatacontained
withinastring.Inthiscase,InStrBreturnsthebytepositionof
stringtofind,asopposedtothecharacterposition.

VBA/VBScriptDifferences


InVBA,thedefaultvalueofthecompareparameteris
determinedbythesettingoftheOptionComparestatement.
VBScript,however,doesnotsupporttheOptionCompare
statement,andcomparemodedefaultstovbBinaryCompare.

SeeAlso
InstrRevFunction,Left,LeftBFunctions,Mid,MidBFunctions,
Right,RightBFunctions,StrCompFunction


InstrRevFunction

Syntax

InstrRev(sourcestring,soughtstring[,start[,compare]])
sourcestring
Use:Required
DataType:String
Thestringtobesearched.
soughtstring
Use:Required
DataType:String
Thesubstringtobefoundwithinsourcestring.
start
Use:Optional
DataType:Numeric
Startingpositionofthesearch.Ifnovalueisspecified,
startdefaultsto1.
compare
Use:Optional
DataType:Integer


Themethodthatcomparessoughtstringwith
sourcestring;itsvaluecanbevbBinaryCompareor
vbTextCompare

ReturnValue
VariantoftypeLong.

Description
Determinesthestartingpositionofasubstringwithinastring
bysearchingfromtheendofthestringtoitsbeginning.


RulesataGlance
WhileInStrsearchesastringfromlefttoright,InStrRev
searchesastringfromrighttoleft.
vbBinaryCompareiscase-sensitive;thatis,InstrRev
matchesbothcharacterandcase,whereasvbTextCompare
iscase-insensitive,matchingonlycharacter,regardlessof
case.
ThedefaultvalueforcompareisvbBinaryCompare.
startdesignatesthestartingpointofthesearchandisthe
numberofcharactersfromthestartofthestring.
Ifstartisomitted,thesearchbeginsfromthelast
characterinsourcestring.
sourcestringisthecompletestringinwhichyouwantto
findthestartingpositionofasubstring.


Ifsoughtstringisn'tfound,InStrRevreturns0.
Ifsoughtstringisfoundwithinsourcestring,thevalue
returnedbyInStrRevisthepositionofsourcestringfrom
thestartofthestring.

ProgrammingTipsandGotchas
OneoftheusefulapplicationsofInstrRevistosearchbackward
throughapathandfilenametoextracteachsuccessive
component.

Example
ThisexampleusesbothInStrandInStrRevtohighlightthe
differentresultsproducedbyeach.Usingasourcestringthat
states"IlikethefunctionalitythatInStrRevgives,"InStrfinds

thefirstoccurrenceof"th"atcharacter8,whileInStrRevfinds
thefirstoccurrenceof"th"atcharacter26:
DimmyString
DimsSearch
myString="IlikethefunctionalitythatInStrRevgives"
sSearch="th"
MsgboxInStr(myString,sSearch)
MsgboxInStrRev(myString,sSearch)

SeeAlso
InStr,InStrBFunctions








RegExp.PatternProperty

DataType
String

Description
Containsapatternstringthatdefinesthesubstringtobefound
inasearchstring.

RulesataGlance
Thefollowingtabledefinesthemeaningoftheindividual

charactersthatcanbeincludedinthepatternstring.Thetable
inthe"ProgrammingTipsandGotchas"sectionlistsapattern
stringusingeachsymbolandshowstheresultsreturnedbythe
Executemethod.
Symbol

Description
Marksthenextcharacteraseitheraspecialcharacter(suchas\nforthenewline
character)orasaliteral(ifthatcharacterotherwisehasspecialmeaningina
patternsearchstring).Thespecialcharactersare:
\f
formfeedcharacter
\n
newlinecharacter

\

\r
carriagereturncharacter
\t


tabcharacter
\v
verticaltabcharacter
^

Matchesthebeginningofinput.

$


Matchestheendofinput.

*

Matchestheprecedingatomzeroormoretimes.

+

Matchestheprecedingatomoneormoretimes.

?

Matchestheprecedingatomzerooronetime.

.

Matchesanysinglecharacterexceptanewlinecharacter.
Definesasubexpressionwithinthelargersubexpression.Asubexpression:
Overridestheorderofprecedenceusedinevaluatingpatternstrings.

()

Canbereferencedagaininthepatternstring.Toinserttheresultofthe
subexpressionlaterinthepatternstring,referenceitbyitsone-based
ordinalpositionamongsubexpressions,precededbythebackslashsymbol
(e.g.,\1).Seetheexampleusingthe\numsyntaxinthe"ProgrammingTips
andGotchas"section.
Canbereferencedagaininthereplacementstringincallstothe
RegExp.Replacemethod.Tousetheresultoftheoriginalsubexpressionasa

replacementstring,referenceitsone-basedordinalpositionamong
subexpressions,precededbyadollarsign(e.g.,$1).SeeRegExp.Replace
Methodforanexample.

x|y

Matcheseitherxory.

{n}

Matchesexactlyntimes,wherenisanonnegativeinteger.

{n,}

Matchesatleastntimes,wherenisanonnegativeinteger.o{1,}isthesameas
o+,ando{0,}isthesameaso*.

{n,m}

Matchesatleastnandatmostmtimes,wheremandnarenonnegativeintegers.
o{0,1}isthesameaso?.


[abc]

Matchesanyoneoftheenclosedcharacters(representedbyabc)inthecharacter
set.

[^xyz]


Matchesanycharacter(representedbyxyz)notenclosedinthecharacterset.For
example,[^abc]matchesthe"p"in"plain."

[a-z]

Matchesanycharacterinarangeofcharacters(representedbya-z).

[^m-z] Matchesanycharacternotincludedinarangeofcharacters(representedbym-z).

\b

Matchesawordboundary;thatis,thepositionbetweenawordandaspace.The
wordboundarysymboldoesnotincludenewlinecharactersortheendofinput
(seethe\ssymbol).

\B

Matchesanonwordboundary.ea*r\Bmatchesthe"ear"in"neverearly."

\d

Matchesadigitcharacter.Equivalentto[0-9].

\D

Matchesanondigitcharacter.Equivalentto[^0-9].

\s

Matchesanywhitespace,includingspace,tab,form-feed,etc.Equivalentto[

\f\n\r\t\v].

\S

Matchesanynonwhitespacecharacter.Equivalentto[^\f\n\r\t\v].

\w

Matchesanywordcharacterincludingunderscore.Equivalentto[A-Za-z0-9_].

\W

Matchesanynonwordcharacter,includingwhitespaceandcarriagereturns.
Equivalentto[^A-Za-z0-9_].

\num

Matchesthesubexpression(enclosedinparentheses)whoseordinalpositionin
thepatternisnum,wherenumisapositiveinteger.

\n

Matchesn,wherenistheoctalvalueofanASCIIcode.Octalescapevaluesmust
be1,2,or3digitslongandmustnotexceed256;iftheydo,onlythefirsttwo
digitsareused.

\xn

Matchesn,wherenisthehexadecimalvalueofanASCIIcode.Hexadecimal
escapevaluesmustbetwodigitslong.



ProgrammingTipsandGotchas
ThefollowingtableshowsasearchstringandtheValue
propertyofeachMatchobjectreturnedbytheExecutemethod
whenthestring:
"Tobeornottobe.Thatisthequestion."&vbCrLf&_
"Whether'tisnoblerinthemindtoendure..."
ispassedtotheExecutemethod.TheRegExpobject'sGlobal
propertyissettoTrue,anditsIgnoreCasepropertyissetto
True.
Pattern

Matches

\n.....

Wheth

^.....

Tobe

.....$

re...

no*

no,n,no,n,n,n(6matches)


no+

no,no(2matches)

bo*e?

be,be,b(3matches)

qu...

quest

th(at|e)

That,the,the,the(4matches)

to|i

To,to,i,i,i,i,i,to(8matches)

\.{3}

...

\.{2,}

...



\.{1,3)

.,.,...(3matches)

i[nst]

is,is,in,in(4matches)

[^bhm]e

ue,le,e,re(4matches)

[r-z]o

To,to,to(3matches)

[^o-z]o

o,no,io,no(4matches)

.o\b

To,to,to(3matches)

.o\B

o,no,io,no(4matches)

\d


(0matches)

\D\.\b

e.,n.(2matches)

...\s

be,not,be.,hat,the,on.,her,tis,ler,the,ind(11matches)

\b\S{3}\b

not,the,tis,the(3matches)

\w{3}\.\s

ion.

\W{3}

.(vbCrLf),...(2matches)

(\S+)
(\s+)\S+\2\S+\2\S+\2

Tobeornot,tobe.Thatis,Whether`tisnoblerin(3
matches)

\164\157


To,to,to(3matches)

\x74\x6f

To,to,to(3matches)

Searchesusingregularexpressionscanbequitecomplex.If
you'reinterestedinabookthatdealsexclusivelywithregular
expressionsandpatternsearches,seeMasteringRegular
Expressions,writtenbyJeffreyE.Friedl(O'Reilly).


Example
Thefollowingroutineallowsyoutoexperimentwithsearches
usingregularexpressions.Whenyoucallit,justpassthestring
you'dliketosearch.Adialogappearsrepeatedly,prompting
youforapatternstring,followedbyanotherdialogthat
displaystheresultsofthesearchusingtheregularexpression
you'veentered.Whenyou'refinished,simplyclicktheCancel
buttontoexittheroutine:
PublicSubSearchExp(strSearch)
DimoRegExp,colMatches,oMatch
DimstrPattern
SetoRegExp=NewRegExp
oRegExp.Global=True
oRegExp.IgnoreCase=True
Do

strPattern=InputBox("Enterpatternstring:","Pattern","
ifstrPattern=""then

ExitDo
Else
oRegExp.Pattern=strPattern
endIf
strMsg="Pattern:"&oRegExp.Pattern

SetcolMatches=oRegExp.Execute(strSearch)
strMsg=strMsg&",Matches:"&colMatches.Count&vbcrlf
ifcolMatches.Count>0Then
foreachoMatchincolMatches
strMsg=strMsg&oMatch.Value&vbCrLf
next
Else


strMsg=strMsg&"Nomatchfound"
EndIf
MsgBoxstrMsg
Loop
EndSub

SeeAlso
RegExpObject,RegExp.ExecuteMethod,RegExp.Replace
Method,RegExp.TestMethod


×