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

如何在.find方法中使用逻辑或?查找'a'或'b'返回-1的正确写法

嘿,我来帮你搞定这个问题!你遇到返回-1的情况,大概率是因为没正确处理「查找a或b」的逻辑——很多新手会踩坑,比如直接用str.find('a' or 'b')这种写法,这其实只会检查第一个“真值”(也就是'a'),如果目标里没有'a'就直接返回-1,完全不会去查'b'。

下面分几种常见编程语言给你正确的实现方式:

正确写法示例

Python 实现

有两种实用的方式:

  • 方式一:分别查找后取有效索引
target = "你的目标字符串"
# 分别获取a和b的索引
idx_a = target.find('a')
idx_b = target.find('b')

# 处理结果:如果至少一个存在,取最小的索引;都不存在返回-1
result = min(idx_a, idx_b) if (idx_a != -1 or idx_b != -1) else -1
  • 方式二:用正则表达式更简洁
import re
target = "你的目标字符串"
match_obj = re.search(r'[ab]', target)
# 找到就取起始索引,没找到返回-1
result = match_obj.start() if match_obj else -1

JavaScript 实现

同样有两种思路:

  • 方式一:分别调用indexOf判断
const target = "你的目标字符串";
const idxA = target.indexOf('a');
const idxB = target.indexOf('b');

let result = -1;
if (idxA !== -1 && idxB !== -1) {
  result = Math.min(idxA, idxB);
} else if (idxA !== -1) {
  result = idxA;
} else if (idxB !== -1) {
  result = idxB;
}
  • 方式二:正则匹配
const target = "你的目标字符串";
const match = target.match(/[ab]/);
const result = match ? match.index : -1;
关键提醒

核心错误点在于不要用逻辑或(or/||)直接连接两个查找字符,比如target.find('a' or 'b')这种写法是逻辑错误——逻辑或在这里只会返回第一个为真的字符,不会同时检查两个目标字符。只要避开这个坑,按照上面的方法实现就能正确找到'a'或'b'的索引啦。

内容的提问来源于stack exchange,提问作者El-bigode

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:48:19