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

如何从string array中筛选首字符为数字、次字符为字母的元素?

筛选符合规则的字符串元素

下面是几种主流编程语言的实现方案,核心逻辑均为验证字符串的第一个字符为数字、第二个为字母,同时规避字符串长度不足2的异常情况:

JavaScript 实现

方案1:直接字符判断

const strArray = ["1a", "b2", "3C", "45", "d6", "z"];
const result = strArray.filter(str => {
  if (str.length < 2) return false;
  const firstChar = str[0];
  const secondChar = str[1];
  return !isNaN(parseInt(firstChar)) && /[a-zA-Z]/.test(secondChar);
});
console.log(result); // 输出: ["1a", "3C"]

方案2:正则表达式匹配

用正则/^\d[a-zA-Z]/直接匹配字符串开头的规则,写法更简洁:

const strArray = ["1a", "b2", "3C", "45", "d6", "z"];
const result = strArray.filter(str => /^\d[a-zA-Z]/.test(str));
console.log(result); // 输出: ["1a", "3C"]

Python 实现

方案1:循环遍历判断

str_array = ["1a", "b2", "3C", "45", "d6", "x"]
result = []
for s in str_array:
    if len(s) >= 2 and s[0].isdigit() and s[1].isalpha():
        result.append(s)
print(result)  # 输出: ['1a', '3C']

方案2:列表推导式简化

str_array = ["1a", "b2", "3C", "45", "d6", "x"]
result = [s for s in str_array if len(s)>=2 and s[0].isdigit() and s[1].isalpha()]
print(result)

Java 实现

import java.util.ArrayList;
import java.util.List;

public class FilterTargetStrings {
    public static void main(String[] args) {
        String[] strArray = {"1a", "b2", "3C", "45", "d6", "y"};
        List<String> result = new ArrayList<>();
        
        for (String s : strArray) {
            if (s.length() >= 2) {
                char firstChar = s.charAt(0);
                char secondChar = s.charAt(1);
                if (Character.isDigit(firstChar) && Character.isLetter(secondChar)) {
                    result.add(s);
                }
            }
        }
        
        System.out.println(result); // 输出: [1a, 3C]
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 01:27:36