【问题标题】:How to find the index of words matched in a text?如何找到文本中匹配的单词的索引?
【发布时间】:2019-02-08 10:23:57
【问题描述】:

我正在提取与this regex 匹配的词的索引。它使用正则表达式匹配文本中所有必需的单词,但它也匹配正则表达式左侧的空格。它不是在左侧的文本中限制匹配的字符串,而是使用\b来限制匹配字符串的右侧

正则表达式:

(price|rs)?\s*(\d+[\s\d.]*\s*?(pkg|k|m|(?:la(?:c|kh|k)|crore|cr)s?|l)\b\.?)

输入文字:

    This should matchprice  5.6 lacincluding price(i.e  price 5.6 lac) and rs 56 m. including rs (i.e rs 56 k  rs 56 m) .

It will match normally if there is no price or rs written for example or                   56 k or   8.8 crs.   are  correct matching but its should bound the matched string from left side as well just like its not matching sapce after end of the matched string.

It should not match the spaces left of 8.5 in this      8.5 lac ould not match eitherrs 6 lac asas there is no spaces before 5.6

How can I modify above regex to bound the matched word in the left side as well? 

【问题讨论】:

    标签: python regex regex-group


    【解决方案1】:

    您可以将\s* 移动到可选的非捕获组中:

    (?:\b(price|rs)\s*)?(\d+[\s\d.]*\s*?(pkg|k|m|(?:la(?:c|kh|k)|crore|cr)s?|l)\b\.?)
    ^^^^^^^^^^^^^^^^^^^^
    

    regex demo

    (?:\b(price|rs)\s*)? 模式将匹配单词边界,后跟 pricers,后跟 0+ 个空格字符,整个模式将尝试一次,由于 @987654327,该模式是可选的@修饰符(整个模式序列可以匹配1次或0次)

    【讨论】:

    • 感谢@Wiktor 的回答。我会检查的。
    猜你喜欢
    • 2021-10-25
    • 2014-08-18
    • 2020-06-08
    • 2018-12-08
    • 2011-08-29
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多