You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java实现字符串替换:含小数点则保留点后内容

解决方案:提取小数点后的字符串内容

下面提供两种简洁可行的实现方式(以下以Python为例,其他编程语言逻辑可直接复用):

方法一:字符串分割(split)法

利用字符串分割特性,直接取分割后的最后一部分。若字符串不含小数点,分割结果仅一个元素,取最后一项等价于原字符串,完美适配需求。

def get_content_after_dot(s):
    return s.split('.')[-1]

# 测试验证
print(get_content_after_dot("ABC.eee"))  # 输出: eee
print(get_content_after_dot("hello_world"))  # 输出: hello_world
print(get_content_after_dot("file.name.with.multi.dots"))  # 输出: dots

方法二:正则表达式法

通过正则匹配处理小数点前后内容,无小数点时直接返回原字符串。

实现方式1:替换匹配内容

import re

def get_content_after_dot(s):
    # ^.*\. 匹配从开头到最后一个小数点的所有内容,替换为空
    return re.sub(r'^.*\.', '', s)

# 测试验证
print(get_content_after_dot("ABC.eee"))  # 输出: eee
print(get_content_after_dot("hello_world"))  # 输出: hello_world
print(get_content_after_dot("file.name.with.multi.dots"))  # 输出: dots

实现方式2:精准捕获目标

如果需要更明确地定位目标内容,可使用search方法直接捕获小数点后的部分:

import re

def get_content_after_dot(s):
    match_result = re.search(r'\.(.*)$', s)
    return match_result.group(1) if match_result else s

# 测试验证
print(get_content_after_dot("ABC.eee"))  # 输出: eee
print(get_content_after_dot("hello_world"))  # 输出: hello_world
print(get_content_after_dot("file.name.with.multi.dots"))  # 输出: dots

方法对比

  • split法:无需额外依赖,代码简洁直观,适合基础场景。
  • 正则法:灵活性更强,后续若需求变动(比如仅保留第一个小数点后的内容),只需调整正则表达式即可。

内容的提问来源于stack exchange,提问作者hong kun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 20:06:28