29

I'm trying to match certain text and then replace with the text plus some extra characters. Minimal example text:

#10 Oranges. These are citrus fruits

Desired output:

#10 Oranges. These are citrus fruits

Regex: (#\d{1,2}[^.]*\.)\s*

Replace with: $1\n

(I have Match using regular expressions checked)

The regex successfully matches #10 Oranges.. However the numbered backreference doesn't replace the text with the capture group but just goes in literally (literal output is $1\n). I have also tried using a backslash for the numbered backreference \1 and the result is the same.

Is there something I'm missing? How do I reinsert matched text in google docs using regular expressions?

User
  • 613
  • 2
  • 7
  • 16

2 Answers2

8

Short answer

Instead of using the built-in find and replace function use Google Apps Script or an add-on.

Explanation

On the Find and Replace feature of Google Documents, the Replace part doesn't work with regular expressions and it doesn't work either with the replaceText() method from the Documents Service in Google Apps Script fortunately JavaScript replace method works.

To learn the very basics to create a simple script, see https://developers.google.com/apps-script/overview

Code

This code is an adaptation of the one included in the reference

function myFunction() {
  var body = DocumentApp.getActiveDocument().getBody();
  var paragraphs = body.getParagraphs();
  for (var i=0; i<paragraphs.length; i++) {
    var text = paragraphs[i].getText();
    paragraphs[i].replaceText(".*", 
       text.replace(/(\d{1,2}[^.]*\.)\s*/gi, '$1\n') );
  }
}

References

Rubén - Volunteer Moderator -
  • 46,305
  • 18
  • 101
  • 297
5

As stated by user in the comments

Note: Capture groups only work with Google Sheets.

bummi
  • 157
  • 2
  • 3
  • 8
Kelvin
  • 167
  • 1
  • 2