Sei sulla pagina 1di 2

CSS343RegularExpressionhomeworksolutions(CarolZander,CSS343)

Notethatregularexpressionsandgrammarsarenotunique.Yoursmaylook
verydifferentfrommineandstillbecorrect.Askmeifyou'renotsure.
Thesesolutionsuseeither'+'or'|'astheORoperator.
1.RegularexpressionsLetthealphabet={a,b}.Noteeisusedforthe
emptystring.Writeregularexpressionsfor:
Allwordsinwhich'a'appearstripled(andonlytripled,meaningall
a'smustappearingroupsofthree)(theemptystringisvalid).
(aaa|b)*
Allwordsthatcontainatleastoneofthestringss1,s2,s3,s4.
(s1,s2,s3,s4arevariablesrepresentingsomestringofa'sandb's.)
Forexample,s1couldbe"ab"or"abbaa"or"aaa"or"b".
(a|b)*(s1|s2|s3|s4)(a|b)*
Recallthat(a|b)*generatesanystringsofa'sandb's.Sotheremay
bemoreoccurrencesofs1...s4,buttheywillbegeneratedbythe(a|b)*
partoftheregularexpr.Notethat
(a|b)*(s1|s2|s3|s4)(a|b)*=(a|b)*(s1|s2|s3|s4)(s1|s2|s3|s4)*(a|b)*
buttheleftsideismoreconcise.
Allwordsthatcontainexactlythreeb'sintotal.
a*ba*ba*ba*
Itwillonlygeneratethreeb's,buta'scanbeanywhere.
Allwordsthatcontainexactlytwob'sorexactlythreeb's.
a*ba*ba*|a*ba*ba*ba*
Allstringsthatendinadoubleletter.
(a|b)*aa|(a|b)*bbor(a|b)*(aa|bb)
Allstringsthathaveexactlyonedoubleletterinthem.
(b|e)(ab)*aa(ba)*(b|e)|(a|e)(ba)*bb(ab)*(a|e)
Allstringsthatdonothavethesubstring'ab'.
b*a*
2.WritearegularexpressionforallunsignednumbersinPascal.Theyare
stringssuchas5280,39.37,499E3,63.36E4,1.894E3,2.3478E+11.
Youarenotallowedtohaveanakeddecimalpoint.Forexamplethenumber
5.or.5isnotallowed,mustuse5.0and0.5.TheEisforexponent,
essentiallyscientificnotation.
Foreaseinexpressing,calltheregularexpressiontogenerateonedigit,d.
d=0|1|2|3|4|5|6|7|8|9
Notethateisstilltheemptystring.
dd*(e|.dd*)(e|E(+||e)dd*)
Fortheseproblems,thealphabetis{a,b}.
3.Writeregexprforwordswith'b'asthesecondletter.
(a|b)b(a|b)*
4.Writeregexprforwordsbaa,ab,andabb.
baa|ab|abb
5.Writeregexprforonlythosewordsthathaveaneven
numberofletterstotal.

((a|b)(a|b))*
6.Writeregexprforonlythosewordsthatdonotendin"ba".
(a|b)*(aa|ab|bb)|a|b|e
Beginningofthestringcanbeanything,the(a|b)*,then
forcethelasttwoletterstobeanything,but"ba".
Thisgetsthemallexceptforstringswithzerooronecharacter.
7.Letthealphabetbe{0,1}.Writearegularexpressionfor
thesetofallstringsnotcontaining101asasubstring.
Attempt:(00*0|100|11*1|001)*|0|1|01|10|010|...
stillcan'tget10010__
0||1||___
|v|v||
Tryfinitestatemachine:start>+a>+b>+c>trap|
^10|1^|
|_______________________||___|
00,1
Sinceeachstateisfinal,createapartofaregularexpression
foreachstate.
state
(0|11*00)*//a:0loop,thenloop11*togettostateb
//and00togetbacktostatea
|0*11*(1*000*11*)*//b:0*11*togettostateb,thenloop1*0
//togettostatecand00*11*backtob
|0*11*0(00*11*0)*//c:0*11*0togettostatec,thenloop0
//togettostateaand0*11*0backtoc

Potrebbero piacerti anche