简体   繁体   English

正则表达式前缀,只捕获奇数个实例?

[英]Regex prefix, capture only odd number of instances?

I want to capture all mutually exclusive occurrences of strings inside two percentages "%". 我想在两个百分比“%”内捕获所有相互排斥的字符串。 If its between two percentages, it will be flagged as a variable for replacement in my parsing process. 如果它在两个百分比之间,它将在我的解析过程中被标记为替换变量。

So if I have this input string 所以,如果我有这个输入字符串

TLA%HRN%767%BRN%DFS

It should only return "HRN" and "BRN", not "HRN","767",and "BRN". 它应该只返回“HRN”和“BRN”,而不是“HRN”,“767”和“BRN”。

I don't want the 767 because it steals the percentage characters from HRN and BRN. 我不想要767,因为它窃取了HRN和BRN的百分比字符。 I guess I only want to match where there is an odd number of percentage characters in the prefix. 我想我只想匹配前缀中有奇数个百分比字符的位置。

Here is my regex work in progress. 这是我正在进行的正则表达式工作。 It captures the three instances, not just the two I want. 它捕获了三个实例,而不仅仅是我想要的两个实例。

(?<=\b[A-Za-z1-9]+%).+?(?=%)

How do I capture only an odd number of percentage character occurrences in the prefix? 如何在前缀中仅捕获奇数个百分比字符出现次数?

You can use this regex for matching: 您可以使用此正则表达式进行匹配:

%[^%]+%

Reason why it works because once % is consumed in %HRN% trailing % isn't available to return 767 . 之所以%HRN%是因为%消耗%HRN%尾随%无法返回767

Regex Demo 正则表达式演示

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

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