oyeesh
oyeesh

Reputation: 571

Regex to pull out the string between 2 underscores

I have a pattern of type anystring_OPCtarget_anystring. Can I get some help as how to verify if the string between the 2 underscores is of type "OPC(target)" and pull out the target using regex.

Suppose if my string is: MP700000001_OPC32_812345643 first, I need to verify if the string between underscores starts with OPC and then get the target text after OPC and before the 2nd underscore.

Help appreciated!!!

Thank you

Upvotes: 5

Views: 7990

Answers (4)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Use the following approach to get the needed "target":

$str = 'MP700000001_OPC32_812345643';
$target = '';
if (preg_match('/^[^_]+_OPC(\w+)_\w*$/', $str, $matches)) {
    $target = $matches[1];
}

print_r($target);  // 32

Upvotes: 3

Vee20
Vee20

Reputation: 56

If you are using a language that supports lookahead and lookbehind you can do something like this:

    Pattern p = Pattern.compile("(?<=_)OPC[0-9]+(?=_)");
    Matcher m = p.matcher("MP700000001_OPC32_812345643");

    if (m.find()) {
        String target = m.group(0);
        System.out.println(target);
    }

Upvotes: 1

Linnea Gr&#228;f
Linnea Gr&#228;f

Reputation: 239

_([^_]+)_

First capturegroup is text between the two underscores
Explanation:

_([^_]+)_
_                First underscore
 (     )         Capture group
  [^ ]           Everything but this character class
    _            No underscores
      +          One or more times
        _        Closing underscore

Upvotes: 6

anubhava
anubhava

Reputation: 784898

You can use this regex:

^[^_]*_OPC\K[^_]+

And grab matched data.

  • ^[^_]*_OPC will match any text upto first _ followed by OPC.
  • \K will reset all previously matched data
  • [^_]+ will match data after OPC before 2nd _

RegEx Demo

Code:

$str = 'MP700000001_OPC32_812345643';

preg_match('/^[^_]*_OPC\K[^_]+/', $str, $matches);

echo $matches[0] . "\n";
//=> 32

Upvotes: 1

Related Questions