置換(replace、全部、ReplaceAll)
Python
py
s = s.replace('abc', 'ABC') # デフォルト gsub の動作
py
str1 = str1.replace('abc', 'ABC') # with string
str1 = re.sub('abc', 'ABC', str1) # with regexp
Swift
swift
s.replacingOccurrences(of: "abc", with: "ABC")
swift
let name = line.replacingOccurrences(of: " +[0-9(].*$", with: "", options: .regularExpression, range: line.range(of: line))
- Swift の文字列置換や正規表現は、若干クセがあるか
PHP
php
str_replace('before', 'after', $str);
- 4つ目の引数に
$count
が指定できるが、これは 置換した数を受け取るためのもので、回数指 定ではないので注意。
TypeScript
ts
str.replace(/before/g, 'after');
- これだけのために正規表現にしたくない・・
- よく見るのは
s.split('before').join('after')
みたいなやつ。何かでうまく行かなかった記憶
Bash
bash
${str//before/after}
//
だと全部。 /
だと1個。
Ruby
rb
s = s.gsub('abc', 'ABC') # with string
rb
str1 = str1.gsub('abc', 'ABC') # with string
str1 = str1.gsub(/abc/, 'ABC') # with regexp
str1.gsub!('abc', 'ABC') # destructive
gsub : マッチする部分全て
gsub(/パターン/, "置き換え文字列")
gsub(/パターン/) {|matched|
xxxxx
}
PowerShell
powershell
$s -creplace 'before', 'after'
-replace
だと大文字小文字区別なし-creplace
だと大文字小文字区別あり