Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for pandoc-markdown citations

I'm trying to search and replace citations from pandoc-markdown. They have the following syntax:

[prenote @autorkey, postnote]

Or for more than one Author

[prenote1 @authorekey1, postnote1; prenote2 @authorkey2, postnote2]

The pre-notes, the author-keys and the post-notes should each be in their own capture group.

For only one author in a citation I used regex this:

\[((.*) )?@(.*?)(, (.*))?\]

But I can't figure out how to match a citation with multiple authors. Ideally it would be possible to match citations with one or more author keys. The pre-note and the post-note should be optional.

Is this possible?

like image 381
Bonschi Avatar asked Jun 17 '26 16:06

Bonschi


1 Answers

We need more context with code (full sample code) to be able to answer fully, so I can only answer in the same general way in which you asked the question.

I do not believe you can do it in one operation with one regular expression.

So the overall technique I would use is:

  1. First match the entire citation (with one or more authors) using a simple regex with only one group, namely for everything between [ and ].
  2. Then, when a match is found, split what is in that match (i.e. everything between the square brackets) by ; to get a list of "prenote @authorkey, postnote" strings.
  3. Do the wanted replacements on each element in that resulting list of single author strings.
  4. Stitch together the final citation by joining the resulting list with semicolons again and adding [ and ] in around it.
  5. Put that final citation in the original instead of the matched string.

You can put steps 2 to 4 in a function f(match_object), and then use re.sub(pattern, f, string) to do the replacement. It will call function f for each match it finds, and replace that match with the return value of f.

like image 51
Jesper Avatar answered Jun 19 '26 06:06

Jesper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!