Regex to pull out the string between 2 underscores

两盒软妹~` 提交于 2021-02-04 19:44:05

问题


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


回答1:


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



回答2:


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



回答3:


_([^_]+)_

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



回答4:


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);
    }


来源:https://stackoverflow.com/questions/40246908/regex-to-pull-out-the-string-between-2-underscores

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!