0

I'm using this code inside PHP

case preg_match('/\/start( .*)?/', $text):
    echo "got you";
break;

Using this regex all I need to do is catching following structure: $text needs to be:

  • /start

or

  • /start xyz

Where "xyz" stands for random content. These are the two only formats which should be accepted by the regex. For some reason my regex seems to be not working as expected.

6
  • 1
    And the question is? Commented Jun 1, 2017 at 17:32
  • Excuse me, I edited. Commented Jun 1, 2017 at 17:34
  • 1
    What happens with your regex? It works as I'd expect. What is your switch looking like? Commented Jun 1, 2017 at 17:35
  • Use a caret to assert beginning of input string ^\/start( .*)? Commented Jun 1, 2017 at 17:37
  • Do you only want to match those two formats? /start and /start xyz and not something like /start xyz xyz? If so, then is this what you are looking for? Commented Jun 1, 2017 at 17:39

1 Answer 1

1

This should do the trick:

^\/start\s?[\S]*$

Here is an example in python DEMO:

import re

textlist = ["^/start xyz","/start","/start not to match"]

regex = "^/start\s?[\S]*$"

for text in textlist:
    thematch = re.search(regex, text)
    if thematch:
        print ("match found")
    else:
        print ("no match sir!")

What it's doing: the line starts with /start and might have space, then there might be any amount of non space (including none) and then the line ends.

Hopefully that helps!

EDIT;
PHP version of this code.

$textlist = array("^/start xyz","/start","/start not to match");

$regex = "#^/start\s?[\S]*$#";

foreach($textlist as $text){
    preg_match($regex, $text, $thematch);
    if ($thematch){
        print ("match found\n");
    }else{
        print ("no match sir!\n");
    }
}

Demo here: https://3v4l.org/OFpnG

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot. Any suggestions how to make the regex "require" a second parameter, meaning only things like: /start xyz will be accepted (xyz stands for random content)?
Sure! If you change the [\S]* to a [\S]+ it will mean that there has to be at least 1 item. The * means none or any number, the + means 1 or more.
@seikzer if you found this answer helpful please accept it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.