Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
894 views
in Technique[技术] by (71.8m points)

preg match - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use this regex:

^[^_]*_OPCK[^_]+

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('/^[^_]*_OPCK[^_]+/', $str, $matches);

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...