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

如何在Slate Platform Editor中创建Regex过滤器及过滤对象集?

在Slate编辑器中实现正则表达式过滤器及对象集构建

核心逻辑

Slate的正则过滤器依赖自定义编辑钩子和节点遍历,通过监听文本变化或遍历已有内容,用正则匹配筛选目标内容;对象集则用于存储匹配结果的结构化数据(如内容、位置等)。

1. 定义正则过滤规则

  • 根据需求编写对应正则表达式,比如匹配邮箱:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g
  • 封装可复用的匹配函数:
    const matchRegex = (text, regex) => {
      return text.match(regex) || [];
    };
    

2. 集成过滤器到Slate编辑流程

利用Slate的onChange钩子实时监听文本变化,对所有文本节点执行正则匹配:

import { useState } from 'react';
import { Slate, Editable, withReact } from 'slate-react';
import { createEditor, Transforms } from 'slate';

const MyEditor = () => {
  const initialValue = [{ type: 'paragraph', children: [{ text: '输入文本测试正则过滤,比如test@example.com' }] }];
  const [value, setValue] = useState(initialValue);
  const regex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;

  const handleChange = (newValue) => {
    // 遍历所有文本节点执行匹配
    Transforms.nodes(newValue, {
      match: n => n.type === 'text',
      fn: (node, path) => {
        const matches = matchRegex(node.text, regex);
        if (matches.length > 0) {
          // 此处可添加匹配后的处理逻辑,比如高亮、存入对象集
          console.log('匹配到内容:', matches);
        }
      }
    });
    setValue(newValue);
  };

  const editor = withReact(createEditor());

  return (
    <Slate editor={editor} initialValue={initialValue} onChange={handleChange}>
      <Editable />
    </Slate>
  );
};

export default MyEditor;

如果需要高亮匹配内容,可自定义mark节点包裹匹配文本:

// 自定义高亮节点
const Highlight = ({ attributes, children }) => {
  return <span {...attributes} style={{ backgroundColor: 'yellow' }}>{children}</span>;
};

// 注册高亮节点到编辑器
const withHighlight = (editor) => {
  const { renderElement } = editor;
  editor.renderElement = (props) => {
    if (props.element.type === 'highlight') {
      return <Highlight {...props} />;
    }
    return renderElement(props);
  };
  return editor;
};

// 在匹配逻辑中替换文本为高亮节点
Transforms.insertNodes(editor, {
  type: 'highlight',
  children: [{ text: match[0] }],
});

3. 构建带正则过滤的对象集

  • 声明状态变量存储匹配对象,包含内容、位置等结构化信息:
    const [filteredObjects, setFilteredObjects] = useState([]);
    
  • 编写更新逻辑,添加去重避免重复存储:
    const updateFilteredObjects = (matches, path) => {
      const newObjects = matches.map(content => ({
        content,
        path: JSON.stringify(path),
        timestamp: Date.now()
      }));
      // 去重处理
      const uniqueObjects = [...new Set([...filteredObjects, ...newObjects].map(obj => JSON.stringify(obj)))]
        .map(str => JSON.parse(str));
      setFilteredObjects(uniqueObjects);
    };
    
  • 在handleChange的匹配逻辑中调用该函数:
    if (matches.length > 0) {
      updateFilteredObjects(matches, path);
    }
    

4. 批量过滤已有内容

如果需要对编辑器初始内容批量过滤,可在组件挂载时执行遍历匹配:

import { useEffect } from 'react';

useEffect(() => {
  Transforms.nodes(value, {
    match: n => n.type === 'text',
    fn: (node, path) => {
      const matches = matchRegex(node.text, regex);
      if (matches.length > 0) {
        updateFilteredObjects(matches, path);
      }
    }
  });
}, []); // 仅挂载时执行一次

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 03:05:12