Skip to content

Translate string search-and-replace operator #83

Description

@clarity20

Main idea:

${str/x/y}  -->  re.sub(r'x', 'y', str)
${str//x/y}  -->  re.sub(r'x', 'y', str, count=1)

POSIX globs -- N.B., these are not regexes! -- need to be ported to pythonic regexes -- not globs:

abc*  -->  r'abc.*'
ab?c  -->  r'ab.c'
abc[def]  -->  r'abc[def]' (no change)

Extended globs are transformed by moving the operator to the end -- I don't know about !, however:

+(aa|bb)  -->  (aa|bb)+
?(aa|bb)  -->  (aa|bb)?
*(aa|bb)  -->  (aa|bb)*
@(aa|bb)  -->  (aa|bb)@

The real challenge is when expansion is needed. Suppose t='+(xx|yy)' Then the following is NOT correct:

str=ddddxxdddd
echo ${str/$t/qqq}   -->  print(re.sub(t, 'qqq', str, count=1)) 

because to achieve the same effect in python we would need to adjust t: t='(xx|yy)+'.
Probably the best solution is to alter t on the fly when it's needed in calls to re.sub():

re.sub(t, ...)  -->  re.sub(to_regex(t), ...)

for a suitably defined to_regex(). But is that worth the trouble?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions