0

I want to use round brackets for using logical operators, but without making a group for matching.

I’ll explain with an example:

/(synn|pack)\sRim.*?vert(\s\d*cm|\d*cm)/

The first group is (synn|pack). How can I make it OR without making it a group, so than in this regex I'll have only one group (\s\d*cm|\d*cm)?

alexwlchan
  • 4,580
  • 5
  • 31
  • 44
Src
  • 3,905
  • 3
  • 22
  • 50

1 Answers1

1

You should use a non-capturing group. If the first characters after the opening parens of a group are ?:, then the group isn’t captured. So in this example, you’d replace the (synn|pack) group with (?:synn|pack).

Here’s an illustration with Python (the .groups attribute counts how many groups a regex has):

>>> import re
>>> re.compile(r'(synn|pack)\sRim.*?vert(\s\d*cm|\d*cm)').groups
2
>>> re.compile(r'(?:synn|pack)\sRim.*?vert(\s\d*cm|\d*cm)').groups
1

See this Stack Overflow question for more details.

Community
  • 1
  • 1
alexwlchan
  • 4,580
  • 5
  • 31
  • 44
  • Thank you for the answer! – Src Feb 03 '17 at 16:09
  • Could you please tell me how can i make every group after ``OR`` be the first group. ``(?:-(\d*) | \s(\d*) | (\d*))cm`` - Here i have 3 groups – Src Feb 03 '17 at 16:13
  • @Src: What is the regex flavor? What you ask for is not possible in some languages. (BTW, the example above can be written as `[-\s]?(\d*)`) – Wiktor Stribiżew Feb 03 '17 at 16:15