-2

I want to be able to match a regex pattern when the middle of a string could change. I am doing this while reading output of a command, so I need to match for other words in the output as well.

As a small example of what I am trying to achieve,

str1 = 'This is my SAS test'
str2 = 'This is my SATA test'

I want to make a regex pattern that will match both str1 and str2 while keeping the other text in the pattern.

The only way I see that I can acheive this is by making the regex pattern

'This is my SAS test|This is my SATA test'

I would really like it if I could make it simple and just have something like this (I know this doesn't work):

'This is my SAS|SATA test'

Any ideas?

krisharmas
  • 211
  • 2
  • 5
  • 12

2 Answers2

1

Use a group: This is my (SAS|SATA) test.

CollinD
  • 7,304
  • 2
  • 22
  • 45
blm
  • 2,379
  • 2
  • 20
  • 24
1

You'll want to use a group. If you don't want to capture it, use a non-capturing group like so:

/This is my (?:SAS|SATA) test/

This is due to the alternation operator having absolute minimum precedence. By grouping it, it can then process the subexpression properly.

CollinD
  • 7,304
  • 2
  • 22
  • 45