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

无需正则表达式,优雅修改下划线分隔文件名指定字段的方法

Clean, Regex-Free Way to Replace Target Field in Filenames

Got it, let's fix this without messy repeated splits or regex. The key is to split the filename strategically only where we need to, then reconstruct it cleanly.

Approach 1: Split on the last underscore (most concise)

Since your target field is the last segment before the file extension, we can split the filename once at the final underscore to separate the prefix from the target+suffix part. Then we just replace the target part and rejoin:

frameNumber = "&example"  # Your replacement string here
image_name = "centerOne_camera_2_2018-04-11_15:11:21_2.0.jpg"

# Split into prefix (everything before last underscore) and target+suffix
prefix, target_with_suffix = image_name.rsplit('_', 1)
# Extract the file extension (e.g., .jpg)
_, suffix = target_with_suffix.split('.', 1)
# Build the new filename
new_name = f"{prefix}_{frameNumber}.{suffix}"

This gives you exactly the format you want: centerOne_camera_2_2018-04-11_15:11:21_&example.jpg

Approach 2: Split all segments and replace the target index

If you prefer working with all the underscore-separated parts explicitly, you can split once, replace the specific segment, then rejoin. This is great if you might need to modify other segments later:

frameNumber = "&example"
image_name = "centerOne_camera_2_2018-04-11_15:11:21_2.0.jpg"

parts = image_name.split('_')
# Extract the suffix from the last part
suffix = parts[-1].split('.')[1]
# Replace the target segment (the one containing 2.0) with your new string + suffix
parts[-1] = f"{frameNumber}.{suffix}"
# Rejoin all parts with underscores
new_name = '_'.join(parts)

Why this is better than your original approach

  • No repetitive split('_') calls (which are inefficient and hard to read)
  • Uses proper string joining with underscores (so you don't end up with concatenated text like centerOnecamera2...)
  • Dynamically extracts the file extension instead of hardcoding it (works for .png, .jpeg, etc., too)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:43:50