function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ruparuparuparupa 

文末が特定文字のときに置換したい

お世話になっております。

Apexで、文末が特定文字のときに置換したいのですが、
どのように実装すれば良いでしょうか。

replaceメソッドを使えば良いのかなと思ったのですが、
置換する特定文字が文末にあるというのはどのように判断すれば良いのでしょうか。
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm#apex_System_String_replace

どうぞよろしくお願いいたします。
Best Answer chosen by ruparupa
Shingo YamazakiShingo Yamazaki
ruparupaさん

こんにちは。
山﨑と申します。

replace メソッドは正規表現に対応していなさそうですが、replaceAll だと対応してますので
正規表現 + replaceAll で実現する、という方法が考えられます。
 
String specialChar = '。';
String regExp = specialChar + '$';
String replaceMent = '!';

String s1 = 'はじめまして。';
String s2 = 'こんにちは。よろしくお願いします';

// 結果は「はじめまして!」
System.debug(LoggingLevel.INFO, s1.replaceAll(regExp, replacement));

// 結果は「こんにちは。よろしくお願いします」
System.debug(LoggingLevel.INFO, s2.replaceAll(regExp, replacement));

参考:https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm#apex_System_String_replaceAll

All Answers

Shingo YamazakiShingo Yamazaki
ruparupaさん

こんにちは。
山﨑と申します。

replace メソッドは正規表現に対応していなさそうですが、replaceAll だと対応してますので
正規表現 + replaceAll で実現する、という方法が考えられます。
 
String specialChar = '。';
String regExp = specialChar + '$';
String replaceMent = '!';

String s1 = 'はじめまして。';
String s2 = 'こんにちは。よろしくお願いします';

// 結果は「はじめまして!」
System.debug(LoggingLevel.INFO, s1.replaceAll(regExp, replacement));

// 結果は「こんにちは。よろしくお願いします」
System.debug(LoggingLevel.INFO, s2.replaceAll(regExp, replacement));

参考:https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm#apex_System_String_replaceAll
This was selected as the best answer
ruparuparuparupa
山﨑さん

ご回答まことにありがとうございました。
確認できました!
replaceだと正規表現に対応していなかったのですね。

今度ともどうぞよろしくお願いいたします。