php - Regex for starting with and not ends

990

I want to check a string if it starts with dollar ({-code-2}-code-1}) and open brace ({-code-2}) followed by anything but not ends with closing brace (}).

{-code-2}{-code-2}-code-1}this should match {-code-2}{-code-2}-code-1}this shouldn't march}

I tried following:

{-code-2}-code-1}regex = '/(^\{-code-2}\{-code-2}-code-1}).*?(?!\\}){-code-2}-code-1}/';

Is this the correct way?

194

Answer

Solution:

Your question is not completely clear. OK, it is not clear at all.

{-code-1{-code-5}

A lookaround assertion is checking a condition at a certain position in the pattern.{-code-2{-code-5} checks if at a position{-code-3{-code-5} is true and{-code-4{-code-5} is true.

These two conditions will be always true at the end of the string! ==> you are not checking if the string does not end with a{-code-5}:

The anchor{-code-4{-code-5} is true, if the end of the string is ahead, at the same position{-code-3{-code-5} is also true, because there is no{-code-5} ahead.

To test this condition, you have to look back, when{-code-4{-code-5} is found ==>

(?<!\{-code-5}){-code-4{-code-5}
129

Answer

Solution:

I am hazarding a guess that your example was intended to be two separate examples, one of which should match and one of which should not match. The followingregex may do what you want.

<?php
$input1 =    '{$this should match' ;
$input2 = '{$this shouldn\'t march}';
$regex = '/^{\$[^{}]+(?!})$/';

preg_match_all($regex, $input1, $matches); // Will match
var_dump($matches);
preg_match_all($regex, $input2, $matches); // Will not match
var_dump($matches);
?>

People are also looking for solutions to the problem: php - How to change exception message of Exception object?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.