代码之家  ›  专栏  ›  技术社区  ›  Leo

用于标记文本的正向lookahead regex

  •  0
  • Leo  · 技术社区  · 8 年前

    我正在尝试标记以下文本:

    F.B.I. is an acronym. FBI is an acronym, c.i.a. could also be one. $1,000,000.00 is a currency value as well as 1.000.000,00£ for example. Here is a measure cm24.54 and 34.3cm...

    这样地:

    F.B.I. | is | an | acronym | . | FBI | is | an | acronym | , | c.i.a. | could | also | be | one | . | $ | 1,000,000.00 | is | a | currency | value | as | well | as | 1.000.000,00 | £ | for | example | . | Here | is | a | measure | cm | 24,54 | and | 34.3 | cm | ...

    我已经开始编写一个regex来实现这一点,但我不知道如何将缩写词和数字放在一起。

    我的正则表达式如下: str.split(/\s|(?=[^A-Za-z0-9#@])/) ,它拆分并丢弃空白,并拆分非字母数字字符(不包括 # @ )而不是用一个正面的展望来移除它们。

    如何修改正则表达式以拆分上述文本?

    2 回复  |  直到 8 年前
        1
  •  2
  •   Amadan    8 年前

    挑选代币要比挑选漏洞容易得多。只需在列表中查找,修复一些奇怪的东西,移动子表达式,直到它们满足您的要求。记住这一点 A|B , A 有优先权。例如,这似乎适用于上面的代码片段:

    let re = /\$|\£|cm|\.{3,}|[0-9,.]+|(?:\w\.){2,}|[\w.-]+@[\w.-]+|[-\w]+/g;
    let text = "F.B.I. is an acronym. FBI is an acronym, c.i.a. could also be one. $1,000,000.00 is a currency value as well as 1.000.000,00£ for example. Here is an email address email@address.com and a measure cm24.54 and 34.3cm...";
    console.log(text.match(re));

    不过,请注意,这在很大程度上是对例外情况进行编目的工作。肯定会有一些事情你会错过,或者最终会出错,甚至是你需要基于上下文的矛盾规则的情况。

    编辑:这就是我在评论中所说的,但如果你想得很好的话。

    let re = /(\$|\£|cm|\.{3,}|[0-9,.]+|(?:\w\.){2,}|[\w.-]+@[\w.-]+|[-\w]+)/g;
    let text = "F.B.I. is an acronym. FBI is an acronym, c.i.a. could also be one. $1,000,000.00 is a currency value as well as 1.000.000,00£ for example. Here is an email address email@address.com and a measure cm24.54 and 34.3cm...";
    let theSplit = text.split(re);
    console.log("The split:", JSON.stringify(theSplit));
    let stuffBetween = theSplit.filter((e, i) => i % 2 == 0);
    console.log("Just the stuff between:", JSON.stringify(stuffBetween));
        2
  •  0
  •   JGNI    8 年前

    我不认为你可以用正则表达式来做,举个例子 . . 它可以是句子的结尾、小数点、几种欧洲语言中使用的千位分隔符,也可以是腹水省略的一部分 ... 而不是 … . 这个 CLDR project有一些将文本分解成句子的规则。