【问题标题】:Remove all non-latin passages from a string with regex使用正则表达式从字符串中删除所有非拉丁语段落
【发布时间】:2021-10-20 22:33:42
【问题描述】:

我需要从字符串中删除所有包含非拉丁字符的段落,但与我看到的许多答案不同,我还想删除这些段落中的标点符号,同时在英文段落中保留相同的标点符号。

换句话说,当遇到诸如“ָהּ”之类的非拉丁字符时,正则表达式将开始跳过包括 ascii 标点在内的所有内容,直到找到 [a-zA-Z] 字符。

我尝试了以下示例,但它错误地删除了“一半”后的引号,让我相信我对非拉丁字符没有很好的定义。

[\u0250-\ue007][^a-zA-Z]*

这是输入文本的示例(更新):

or perhaps, a - אוֹ דִילְמָא אֵין אִשָּׁה מִתְקַדְּשֶׁת לַחֲצָאִין כְּלָל (12);time
תֵּיקוּ
person cannot be in separate halves at all, even
though both "halves” would come together simultaneously?(13)
The speaker replies:(14)

得到的字符串是:

or perhaps, a - time
person cannot be in separate halves at all, even
though both "halveswould come together simultaneously?(13)
The speaker replies:(14)

如您所见,它在第三行搞砸了。显然,我可以排除那个特定的角色,但我担心它会在其他极端情况下搞砸。

还有其他想法吗? (我正在使用 Javascript 顺便说一句)

【问题讨论】:

    标签: javascript node.js regex


    【解决方案1】:

    我明白,“非拉丁字符,例如 הּ”是指任何非 ASCII 字母。 p>

    要匹配 ASCII 字母以外的任何字母,您可以使用 [^\P{L}a-zA-Z]。这是一个否定字符类,它匹配除非字母字符 (\P{L}) 和 ASCII 字母 (a-zA-Z) 以外的任何字符。所以,它基本上是\p{L} 模式,ASCII 字母除外。

    这种基于 Unicode 字符类的模式需要 u 标志,由 Node.js JavaScript 环境支持。

    解决方案看起来像

    text = text.replace(/[^\P{L}a-z][^a-z]*/gui, '')
    

    注意g 标志使replace 替换字符串中的所有匹配项,i 用于缩短 ASCII 字母模式(因为它使模式匹配不区分大小写)。

    查看 JavaScript 演示:

    const text = `or perhaps, a - אוֹ דִילְמָא אֵין אִשָּׁה מִתְקַדְּשֶׁת לַחֲצָאִין כְּלָל (12);time
    תֵּיקוּ
    person cannot be in separate halves at all, even
    though both "halves” would come together simultaneously?(13)
    The speaker replies:(14)`;
    console.log(
      text.replace(/[^\P{L}a-z][^a-z]*/gui, '')
    )

    输出:

    or perhaps, a - time
    person cannot be in separate halves at all, even
    though both "halves” would come together simultaneously?(13)
    The speaker replies:(14)
    

    【讨论】:

    • 看起来不错!解决了这个问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多