0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Google Document で正規表現にてキャプチャした値を置換後に使う小技

Last updated at Posted at 2022-05-28

Google Document は便利ですが、置換の機能に正規表現がありながら、
キャプチャした値を $1 などで置換後に使えません。
Spreadsheet ならばキャプチャした値を、置換後に$1形式で使えるというのに残念。

「GAS を使ってみればいけるのでは」と思ったのですが、
やはり replaceText というGASの関数では無理でした。

そこでググってみると、うまいこと JavaScript の replace関数と組み合わせてキャプチャ可能にしている方がおられたので、
実装してみると、いけました👍

そんなわけで、メモを残します。

function ReplaceWords(){ 
  const docBody = DocumentApp.getActiveDocument().getBody()
  const paragraphs = docBody.getParagraphs()
  const regExp = '([0-9]{1,2})'//キャプチャ用の任意の正規表現
  paragraphs.map(para => {
    let text = para.getText()
    //GASのreplaceTextの中でreplaceにてキャプチャを使う
    para.replaceText(regExp,
      text.replace(new RegExp(regExp,'g'), '$1hogehoge'))
  })
}

こんな感じです。

これで、無事document上の文字列を、正規表現にて一括置換に成功しました。

便利便利。

参考にしたのはこちら

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?