OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Problem with re.sub and pcre order with regular expressions

  • Thread starter Thread starter Jessica Robin
  • Start date Start date
J

Jessica Robin

Guest
I am trying to understand something I have the following instruction

re.sub(r'\d?(\d\w+|\wb)', 'z', 'ad2aba')

Since it is supposed to replace the expresion d?(\d\w+|\wb)' by z in ad2aba I thought it will give adz since we try to have the longest expression by default

So i thought d? give nothing

d\w+ give 2aba And so we replace it by z and have adz but I am incorrect and the result is actually adza and not adz. The function takes d?\wb instead d\w+ wich gives a longer expression. I do not understand why ? Why choosing that option re.sub is supposed to be greedy and search for the longest one.

Is that the ?d that changes that ?
<p>I am trying to understand something I have the following instruction</p>
<p><code> re.sub(r'\d?(\d\w+|\wb)', 'z', 'ad2aba')</code></p>
<p>Since it is supposed to replace the expresion <code> d?(\d\w+|\wb)'</code> by z in <code>ad2aba</code> I thought it will give <strong>adz</strong> since we try to have the longest expression by default</p>
<p>So i thought <strong>d?</strong> give nothing</p>
<p><strong>d\w+</strong> give <strong>2aba</strong>
And so we replace it by <strong>z</strong> and have <strong>adz</strong> but I am incorrect and the result is actually <strong>adza</strong> and not <strong>adz</strong>. The function takes <strong>d?\wb</strong> instead <strong>d\w+</strong> wich gives a longer expression. I do not understand why ? Why choosing that option re.sub is supposed to be greedy and search for the longest one.</p>
<p>Is that the <strong>?d</strong> that changes that ?</p>
 

Latest posts

Top