user4813136
user4813136

Reputation:

What is the regular expression that generates the language where every odd position in the string is an a?

What is the regular expression that generates the language where every odd position in the string is an a? (Please answer with the shortest possible regex: minimal parentheses, no spaces and any piped strings in alphabetical order!)

I assume I'm working with only a's and b's.

(a(a|b))+ would only cover even strings: a(a|b), a(a|b)a(a|b), etc.

How do I also cover the case that the string is odd? ex: a(a|b)a

Note: not using programming syntax

Edit: some valid strings would be: a, aa, aaa, aaaa, aaaaa, ab, aba, abab, ababa, etc.

EDIT: Solution

My instructor gave the answer (aa|ab)*. This is incorrect because it misses case(s), for example "a".

Upvotes: 0

Views: 2200

Answers (3)

Satya ganesh
Satya ganesh

Reputation: 1

I think this might help you

  • Case 1: even length strings (1(0+1))*
  • Case 2: odd length strings 1((0+1)1)*

Finally the answer is Case 1 + Case 2

Upvotes: 0

Chrᴉz remembers Monica
Chrᴉz remembers Monica

Reputation: 1904

^(a.)*a?$
  • Allows empty values ("")
  • From start to end of line (^...$)
  • Every odd place (1,3,5,...) is an a followed by any letter/number
  • There may or may not be an a in the end
  • One sign shorter thay Jorge's answer, but allows empty values

See regex101 example here

Upvotes: 0

Jorge.V
Jorge.V

Reputation: 1347

I think this suits your requirement:

^a(.a)*.?$
  • Position 1 must be "a": ^a
  • Repetitions of any character + a, making a sequence where odds are "a"'s: (.a)*
  • Allowing for a termination not ending in "a", ex abab: .?$

You can check it here: regex101

Upvotes: 2

Related Questions