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

如何移除字符串中括号、逗号及逗号前内容并保留州缩写

提取字符串末尾的州缩写方案

嘿,我来帮你搞定这个州缩写提取的问题!既然所有字符串格式都是统一的,末尾固定是, 两个大写字母州缩写,完全不用分步去移除逗号、括号,直接用下面这些简洁的方法就能一步到位提取出目标州缩写:

方法1:直接切片(最简单,适合格式绝对统一的场景)

如果能100%保证每个字符串的最后两位就是州缩写,直接取字符串的最后两个字符就行:

Python示例

# 示例字符串
full_str = "Alice Johnson, Chicago, IL"
# 提取最后两位
state_abbr = full_str[-2:]
print(state_abbr)  # 输出: IL

JavaScript示例

const fullStr = "Bob Williams, Miami, FL";
const stateAbbr = fullStr.slice(-2);
console.log(stateAbbr); // 输出: FL

方法2:逗号分割+去空格(更灵活,兼容前面有多个逗号的情况)

如果字符串前面可能有多个逗号(比如包含完整地址),用逗号分割后取最后一部分,再去掉多余空格:

Python示例

full_str = "Charlie Brown, Austin, TX"
# 按逗号分割成列表
parts = full_str.split(',')
# 取最后一个元素并去除前后空格
state_abbr = parts[-1].strip()
print(state_abbr)  # 输出: TX

JavaScript示例

const fullStr = "Diana Prince, Boston, MA";
const parts = fullStr.split(',');
const stateAbbr = parts[parts.length - 1].trim();
console.log(stateAbbr); // 输出: MA

方法3:正则表达式(最精准,能过滤不符合格式的字符串)

如果想确保提取的确实是末尾的两个大写字母州缩写,用正则匹配最稳妥,还能处理异常情况:

Python示例

import re

full_str = "Eve Adams, Seattle, WA"
# 匹配末尾的", 两个大写字母"模式
match = re.search(r', ([A-Z]{2})$', full_str)
if match:
    state_abbr = match.group(1)
    print(state_abbr)  # 输出: WA
else:
    print("字符串格式不符合要求")

JavaScript示例

const fullStr = "Frank Castle, Denver, CO";
const match = fullStr.match(/, ([A-Z]{2})$/);
const stateAbbr = match ? match[1] : "字符串格式不符合要求";
console.log(stateAbbr); // 输出: CO

这些方法都帮你把“移除逗号+提取州缩写”的操作合并成一步了,选最适合你场景的就行!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:35:04