recursion - Recursive regex to check if string length is a power of 3? -


i'm attempting create regex pattern match strings containing periods (.) length power of 3. manually repeat length checks against powers of 3 until length no longer feasible, prefer short pattern.

i wrote python method explain want do:

#n = length def check(n):     if n == 1:         return true     elif n / 3 != n / 3.0:         return false     else:         return check(n / 3) 

to clarify, regex should match ., ..., ........., ..........................., (length 1, 3, 9, 27) etc.

i've read on regex recursion, making use of (?r) haven't been able put works correctly.

is possible?

it can done using regex (handles character, not period):

def length_power_three(string):      regex = r"."      while true:         match = re.match(regex, string)          if not match:             return false          if match.group(0) == string:             return true          regex = r"(?:" + regex + r"){3}" 

but understand want know if can done single regex.

update

i forgot asked recursive solution:

def length_power_three(string, regex = r"."):     match = re.match(regex, string)      if not match:         return false      if match.group(0) == string:         return true      return length_power_three(string, r"(?:" + regex + r"){3}") 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -