字符串替换各语言版本

1 篇文章 0 订阅
1 篇文章 0 订阅

我们写代码的过程中,经常遇到的一类问题就是字符串替换,这里对各个语言做个记录方便查找。
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替换为Jimhello!Jim
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值