字符串替换各语言版本
来源:互联网 发布:南风知我意2七微 编辑:程序博客网 时间:2024/06/05 09:15
我们写代码的过程中,经常遇到的一类问题就是字符串替换,这里对各个语言做个记录方便查找。
1、Ruby
gsub命令
str.gsub(pattern, replacement) orstr.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) orstr.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
阅读全文
0 0
- 字符串替换各语言版本
- C语言 字符串替换
- C语言替换字符串
- 字符串替换C语言
- c语言字符串替换
- 字符串替换(语言入门)
- C语言实现字符串替换
- C语言字符串替换函数
- C语言 字符串替换 多次
- C语言实现字符串替换
- C语言字符串查找替换
- C语言宏定义中的字符串替换
- 用C语言实现字符串替换功能
- c语言中的字符串替换函数
- 用C语言实现字符串替换功能
- C语言中字符替换为字符串
- c语言实现字符串字串的替换
- C语言实现字符串替换函数
- 如何将python脚本生成exe
- centos下安装etherpad
- Redis可视化工具Redis Desktop Manager使用
- EXtjs的可删除,可添加,可移动排序的图片DataView
- poj dfs相关之1011 Sticks
- 字符串替换各语言版本
- C++boost之assign使用(二)
- OC中的一些编程写法--({"添加代码"})
- EXTJS. Grid总计+oracle小计合计
- 补6月20日
- java-对两个数进行加减乘除操作案例
- 详细讨论HashMap
- C语言学习之指针的右左法则
- Nginx负载均衡