我们写代码的过程中,经常遇到的一类问题就是字符串替换,这里对各个语言做个记录方便查找。
1、Ruby
gsub命令
str.gsub(pattern, replacement) or
str.gsub(pattern) { |match| block }
pattern 的所有出现都替换为 replacement 或 block 的值。pattern 通常是一个正则表达式 Regexp;如果是一个字符串 String,则没有正则表达式元字符被解释(即,/\d/ 将匹配一个数字,但 ‘\d’ 将匹配一个反斜杠后跟一个 ‘d’)例如:
irb(main):001:0> "hello!Tom".gsub("Tom","Jim")
=> "hello!Jim"
irb(main):002:0> "hello!Tom".gsub(/Tom/,"Jim")
=> "hello!Jim"
irb(main):003:0> "hello!Tom".gsub(/[Tt]om/,"Jim")
=> "hello!Jim"
irb(main):004:0> "hello!Tom".gsub('/Tom/',"Jim")
=> "hello!Tom"
如果只替换第一次出现的匹配,使用sub方法
str.sub(pattern, replacement) or
str.sub(pattern) { |match| block }
2、python
第一种方式使用字符串的replace方法,原方法定义如下:
class str(basestring):
...
def replace(self, old, new, count=None):
"""
S.replace(old, new[, count]) -> string
Return a copy of string S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
"""
return ""
例如:
>>> str = "hello!Tom"
>>> str.replace("Tom","Jim")
'hello!Jim'
>>> str.replace('o','a')
'hella!Tam'
>>> str.replace('o','a', 1)
'hella!Tom'
使用正则表达式替换,re库的sub方法,
>>> import re
>>> reg = re.complie('Tom')
>>> reg.sub('Jim',str)
'hello!Jim'
>>> reg = re.compile(r'(T|t)om')
>>> reg.sub('Jim',str)
'hello!Jim'
3、java
常用的有replaceAll,replaceFirst,replace这三个方法
replaceAll和replaceFirst方法是两个参数String regex和String replacement
例如
public class MyJava {
// main 方法
public static void main(String[] args) {
// 创建对象,对象名为hello
String str = "hello!Tom";
// 输出结果
System.out.println("Tom替换为Jim:" + str.replaceFirst("Tom","Jim"));
}
}
运行结果:
Tom替换为Jim:hello!Jim