LANG SELRCT

Apps Script Reference  (Create: Create new Spreadsheet | Create new Apps Script

Tuesday, April 30, 2019

正規表現で英数以外のテキストの間にある半角スペースを削除したい


今回試した正規表現

/(?<![a-zA-Z0-9!?])[\s ](?![a-zA-Z0-9])/g



Good morning! お は よ!



Good morning! おはよ!

にする



コード.gs
function doGet() {
  return HtmlService.createHtmlOutputFromFile("index");
}
意訳
この機能がやること
指定したHTMLファイルを表示する




index.html
<!DOCTYPE html>
<html>
<body>
<script>
myFunction();
function myFunction() {
  var text = 'Good morning! お は よ!';
  text = text.replace(/(?<![a-zA-Z0-9!?])[\s ](?![a-zA-Z0-9!?])/g, "");
  console.log(text);
}
</script>
</body>
</html>



補足

.gs側では「SyntaxError: 量指定子 ? は無効です。」と出て ? は使えないようなので、.htmlでやっています。


テキスト画像をOCR化したときに改行が半角スペースになることがあり、その半角スペースを消したくて書きました。


var text = 'Good morning! お は よ!';
text = text.replace(/(?<![a-zA-Z0-9])[\s ](?![a-zA-Z0-9])/g, "");

=> Good morning!おはよ!

これだと ! のあとの半角スペースも消えるので


!と?も対象にして

/(?<![a-zA-Z0-9!?])[\s ](?![a-zA-Z0-9])/g,

としたのが今回試した正規表現です。


Latest post

Extracting data from Google Sheets with regular expressions

Introduction Regular expressions are a powerful tool that can be used to extract data from text.  In Google Sheets, regular expressions ca...