简体   繁体   English

正则表达式获取字符串的第一部分

[英]Regex to get first part of a string

I have this regex 我有这个正则表达式

(?<=\d\.\s).+(?=\s-\s)

It works great when I have a string like 当我有一个字符串像

3. product - sub product

The regex gives me the product (first part). 正则表达式为我提供了产品(第一部分)。 If a sub-product exists it is delimited from the product by a dash surrounded with spaces ( - ). 如果存在子产品,则该产品与产品之间用短划线隔开,并用空格( - )包围。

However, there are some products which do not have sub-product. 但是,有些产品没有子产品。 For example: 例如:

6. ComprehensiveBolt

The regex should give me comprehensiveBolt but it does not return anything. 正则表达式应该给我comprehensiveBolt的螺栓,但它不会返回任何东西。

What update do I need to make to my regex so I can get the product regardless of the presence, or otherwise, of a sub-product? 我需要对正则表达式进行什么更新,以便无论子产品​​是否存在都可以得到该产品?

This is one way. 这是一种方式。
Note this is only needed if your product could be a phrase. 请注意,仅当您的产品可能是短语时才需要。

(?<=\\d\\.\\s)(?:(?!\\s-\\s|\\d\\.\\s).)+

https://regex101.com/r/uC2yDs/1 https://regex101.com/r/uC2yDs/1

Partial explanation 部分说明

 (?<= \d \. \s )               # This must be behind
 (?:                           # -----------
      (?!                           # Neg assertion
           \s - \s                       # Not this ahead
        |  \d \. \s                      # Nor this ahead
      )
      .                             # Ok, grab this character
 )+                            #  1 to many times

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM