简体   繁体   English

正则表达式分组

[英]Regular Expression Grouping

The language I am programming in is Objective C, although that probably has no bearing on solving this problem. 我正在编程的语言是Objective C,尽管这可能与解决此问题无关。

Given 0 to 3 occurrences of 6, 7, 9, 11 and 13 along with their modifiers b or # , how would you write a regex so that you can retrieve the groupings for each value? 给定0至3个出现的6, 7, 9, 11 and 13及其修饰符b# ,您将如何编写一个正则表达式,以便检索每个值的分组? Is regex even the best solution here? 正则表达式甚至是这里最好的解决方案吗? Here's are some examples of some strings that need to be matched: 以下是一些需要匹配的字符串的示例:

Example 1: 7#9  //The groupings should be 7 #9

Example 2: 7b9#13 //The groupings should be 7 b9 #13

Example 3: b6 //The grouping should be b6

Example 4: 7#1311 //The groupings should be 7 #13 11

Example 5: 7911 //The groupings should be 7 9 11

To match just one number like #13, I tried the following: 为了只匹配#13这样的一个数字,我尝试了以下操作:

([#b]?13|11|9|7|6)?

It matches for #13, but not for #11. 它与#13匹配,但与#11不匹配。 I'm really stuck. 我真的被卡住了。

You misplaced the parenthesis. 您放错了括号。 The answer should be this: 答案应该是这样的:

[#b]?(13|11|9|7|6) [#b]?(13 | 11 | 9 | 7 | 6)

Where it looks for the combination of each number with a possible #b 寻找每个数字与可能的#b的组合的地方

instead of 代替

([#b]?13|11|9|7|6)? ([#b]?13 | 11 | 9 | 7 | 6)?

where it only looks for the combination of #13 or 11 or 9 .. etc 它只查找#13或11或9的组合。

The main problem was that the [#|b] set was not being applied to 13, 11, 9, 7 and 6 individually. 主要问题是[#| b]集没有分别应用于13、11、9、7和6。 Also, I duplicated it to handle multiple groupings. 另外,我复制了它以处理多个分组。 Here's the fix: 解决方法是:

([b#]?13|[b#]?11|[b#]?9|[b#]?7|[b#]?6)?([b#]?13|[b#]?11|[b#]?9|[b#]?7|[b#]?6)?([b#]?13|[b#]?11|[b#]?9|[b#]?7|[b#]?6)?([b#]?13|[b#]?11|[b#]?9|[b#]?7|[b#]?6)?

For string b9#1113 it now groups as follows: 对于字符串b9#1113 ,现在将其分组如下:

Group 1: b9 第一组:b9
Group 2: #11 第二组:#11
Group 3: 13 第3组:13

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

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