HarmonyOS鸿蒙Next中正则能拼接识别返回数组吗

HarmonyOS鸿蒙Next中正则能拼接识别返回数组吗

string.split('正则A+正则B') 返回数组 想实现匹配@人和网址
5 回复

【背景知识】

split的主要作用是将字符串拆分为子字符串数组。在ArkTS中,split方法支持传入正则表达式实现字符串的分割,例如"abc, def".split(/, /)。

split的用途主要是分割字符串,而不是匹配内容,若需要实现多匹配功能,可使用match方法。

【解决方案】

使用match方法实现多匹配功能,并返回数组结果。

示例代码如下:

// 待匹配字符串,包含@人和网址
let str = 'Hello @john visit and say hi!'

// 定义正则表达式匹配@人和网址
const pattern = /(@[^\s@]+|https?:\/\/\S+)/g;

// 获取所有匹配项
const matches = str.match(pattern) || [];

// 打印结果
console.log("result#" + matches.toString());

【总结】

split方法只适合用于分割字符串,不适合匹配,match方法可用于字符串的匹配。

更多关于HarmonyOS鸿蒙Next中正则能拼接识别返回数组吗的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


调用实体抽取接口:

doEntityRecognition() {
  textProcessing.getEntity(this.recognizeText, {
    entityTypes: [EntityType.NAME, EntityType.URL]  // 指定需提取的实体类型
  }).then(result => {
    this.formatEntityResult(result);
  }).catch(err => {
    promptAction.showToast({ message: '识别失败' });
  });
}

处理提取结果:

formatEntityResult(entities: textProcessing.Entity[]): void {
  entities.forEach(entity => {
    if (entity.type === EntityType.NAME) {
      // 处理@人逻辑(如 entity.text)
    } else if (entity.type === EntityType.URL) {
      // 处理网址逻辑(如 entity.text)
    }
  });
}

可以试试下面代码:

function splitText(text: string): string[] {
    // 定义正则表达式 - 匹配 @人和网址
    const pattern = /(@[^\s@]+|https?:\/\/\S+)/g;
    
    // 使用 match 方法获取所有匹配项
    const matches = text.match(pattern) || [];
    
    // 使用 split 方法分割字符串,并过滤空字符串
    const parts = text.split(pattern).filter(part => part.trim() !== '');
    
    // 合并分割后的部分和匹配项
    const result: string[] = [];
    let matchIndex = 0;
    
    for (const part of parts) {
        // 如果当前部分是匹配项,则直接添加
        if (matches.includes(part)) {
            result.push(part);
            matchIndex++;
        } else {
            // 否则,检查该部分是否还包含其他匹配项
            const subParts = part.split(/(@[^\s@]+|https?:\/\/\S+)/g);
            for (const subPart of subParts) {
                if (subPart.trim() !== '') {
                    result.push(subPart);
                }
            }
        }
    }
    
    return result;
}

// 测试示例
const text = "大家好,@张三 这是我的个人主页 https://example.com,@李四 也可以看看";
const result = splitText(text);
console.log(result);

在HarmonyOS Next中,正则表达式可以通过RegExp对象进行匹配操作。使用exec()方法执行正则匹配时,若包含捕获组,会返回匹配结果的数组(包含完整匹配及分组捕获内容)。多次调用会持续返回后续匹配,直到返回null。示例:

let regex = /(\w+)\s(\d+)/g;
let result = regex.exec("text 123");
// result为["text 123", "text", "123"]

返回数组结构为:[完整匹配, 分组1, 分组2, …]。全局匹配需循环调用exec()获取所有结果。

在HarmonyOS Next中,可以通过正则表达式拼接实现字符串分割并返回数组。针对您提到的匹配@人和网址的需求,可以使用类似以下方式:

let text = "Hello @张三, visit ";
let pattern = /(@\w+)|(https?:\/\/\S+)/g;
let result = text.split(pattern).filter(item => item); 
// 结果: ["Hello ", "@张三", ", visit "]

关键点说明:

  1. 使用正则表达式/(@\w+)|(https?:\/\/\S+)/g同时匹配@人和网址
  2. split()方法会将匹配到的内容也作为数组元素返回
  3. 通过filter()过滤掉空值

这种方案可以满足同时匹配多种模式的需求,且返回包含匹配结果的数组。

回到顶部