简体   繁体   English

用于提取具有介于和结束模式之间的两个数字的正则表达式

[英]Regex for extracting two numbers with a between and end pattern

I need to extract two numbers under certain conditions: cumulativelly, the first one need to be followed by a /A , AND the second one must be followed by a B .我需要在某些条件下提取两个数字:累积地,第一个数字后面需要跟一个/A ,第二个数字后面必须跟一个B For instance:例如:

  • 30A/305B : both 30 and 305 must be returned; 30A/305B :30和305都必须退回;
  • 30/305B : neither 30 nor 305 would be returned; 30/305B : 30 和 305 都不会返回;
  • 30A/305 : neither 30 nor 305 would be returned; 30A/305 : 30 和 305 都不会返回;

As per here , I tried the regex below without success:根据这里,我尝试了下面的正则表达式但没有成功:

(\d+(?=A\/))(\d+(?=B))

How do I get it done?我该如何完成? I am using R , with option perl = TRUE .我正在使用 R ,带有选项perl = TRUE

The pattern (\\d+(?=A\\/))(\\d+(?=B)) matches 1 or more digits, and asserts (not match) A/ directly to the left.模式(\\d+(?=A\\/))(\\d+(?=B))匹配 1 个或多个数字,并直接在左侧断言(不匹配) A/

That first assertion will be true, but after this assertion there is a second part that starts with matching 1 or more digits again.第一个断言将是真的,但是在这个断言之后,第二部分再次以匹配 1 个或多个数字开始。

That can not work, as the previous assertion just asserted that there is A/这是行不通的,因为之前的断言只是断言存在A/


You don't need any lookarounds or perl = TRUE, you can use 2 capture groups instead:您不需要任何环视或 perl = TRUE,您可以改用 2 个捕获组:

(\d+)A/(\d+)B

Regex demo正则表达式演示

str <- "30A/305B: both 30 and 305 must be returned;"
str_match(str, "(\\d+)A/(\\d+)B")

Output输出

     [,1]       [,2] [,3] 
[1,] "30A/305B" "30" "305"

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

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