DEV Community

Discussion on: Share a code snippet in any programming language and describe what's going on

Collapse
 
auroratide profile image
Timothy Foster

Some regex I wrote in 2018:

/^(?:\*|\d\.)\s(.*)\r?\n([ \t]+(?:\*|\d\.)\s(?:.|\r?\n[ \t]+(?:\*|\d\.))*)/
Enter fullscreen mode Exit fullscreen mode

I've stared at it for 5 minutes and still can't tell you what's happening 🙃

Collapse
 
chrisgreening profile image
Chris Greening

Dear programmer: When I wrote this code, only god and I knew how it worked. Now only god knows it! Therefore, if you are trying to optimize this routine and it fails (most surely), please increase this counter as a warning for the next person: total hours wasted here= 254

Collapse
 
bbrtj profile image
bbrtj

It searches for indented sublists, like:

1. abc
  * def
  * ghi
Enter fullscreen mode Exit fullscreen mode

You're welcome.

Collapse
 
jeremyf profile image
Jeremy Friesen

Lots of (?:\*|\d\.) repeated: non-capture region of either * or (any numeral followed by any character).

Collapse
 
tracygjg profile image
Tracy Gilmore

If you throw the expression into something like Debuggex it can map out the routes through the expression, as follows.

RegExp diagram

However, whilst this shows what is happening it does not indicate why.

Collapse
 
auroratide profile image
Timothy Foster

Now that I'm staring at this chart, I'm recalling that at some point I was trying to parse markdown. Pretty sure this is looking for nested lists:

* Hello!
  1. A nested ordered list
Enter fullscreen mode Exit fullscreen mode

Though, it is interesting to me that the initial * or \d\. is not captured; one would think it'd be important to distinguish between an unordered and ordered list...

Thread Thread
 
tracygjg profile image
Tracy Gilmore

I studied the screenshot I attached to my comment and came to the same conclusion but it looks to me the expression might be more complicated than it needs to be - without fully understanding the context of course.

Collapse
 
jamesthomson profile image
James Thomson

Anyone that can read this and know exactly what's going on is clearly not human