React Native: <string>.matchAll不是一个函数

6

当我运行React Native应用程序时,出现了奇怪的错误:

一些示例代码:

const { url } = <incoming object>;
const reURL   = <my regex>;

console.debug('url:', url);
console.debug('typeof url:', typeof url);

matches = [...url.matchAll(reURL)];

日志输出:

url: <as expected>
typeof url: string

错误信息:

TypeError: url.matchAll is not a function. (In 'url.matchAll(reURL)', 'url.matchAll' is undefined)

iOS 上一切正常,错误只会在 Android 上发生。

环境非常新,几天前更新了所有 npm 包。

有人知道从哪里开始寻找解决方案吗?


这个回答解决了你的问题吗?使用RegExp.exec从字符串中提取所有匹配项的正则表达式 - Kia Kaha
4个回答

1
我有同样的问题。在Android上,String.matchAll不起作用。你应该使用match代替matchAll
例子:
const regex = new RegExp(text, 'ig');
const arr = string.match(regex);

你将获得一个匹配正则表达式的数组


2
string.match与matchAll的功能完全不同。对于多个值的匹配,match仅返回这些值的数组。而matchAll则返回一个迭代器,其值是带有字符串中每个匹配位置的对象,并且还可以处理多个捕获组,而match无法做到这一点。因此,match无法取代matchAll,后者更加实用。 - Christopher Reid

1

0

对我们来说,通过有条件地评估matchAll解决了这个问题:

ourSring.matchAll?.(expr);

我们的工作理论是,第一次访问该方法时,运行了一些本地异步正则表达式初始化,但需要一些时间来绑定该方法,导致matchAll方法未定义。对于我们而言,后续评估工作正常。

0

将调用 str.matchAll(regex) 替换为 this answer 中的递归函数对我来说完美地完成了工作。

为了完整起见,在此粘贴带有 TS 支持的函数:

/**
 * Recursive function which replaces the usage of `str.matchAll(regex)` which happens to be troublesome on Android once compiled.
 * @param regex - regex expression to be executed. If passed with the `/g` global flag the result will return all matches.
 * @param str - string value to be searched for matches by the regex expression
 * @param matches - parameter used to pass on the current resulting array through recursion iterations
 * @returns array of all matches found while executing the regex
 */
export function findAllMatches(regex: RegExp, str: string, matches: RegExpExecArray[] = []) {
  const res = regex.exec(str)
  res && matches.push(res) && findAllMatches(regex, str, matches)
  return matches
}

确保代码库中没有人再次尝试使用matchAll可以通过添加以下es-lint规则来实现:

"no-restricted-syntax": ["error", {
   "selector": "CallExpression[callee.property.name='matchAll']",
   "message": "You should use the findAllMatches function instead."
}]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接