Kusanagi2k
Kusanagi2k

Reputation: 132

Regex to get string after a character ending with another optional character and not matching it

I'm struggling with a regex, here's an example of the input string

test#string=val

i need to get "string" no matter what's inside it (including special charso but bviously not including the '=') it's always preceded by the '#' character, but i don't need it included. The word ahead of it ('test' in this case), is also optional.

The '=' is optional, but if it's there i need it to be ignored. I've been using something like this

#([\w\W]*)

But i can't manage to handle the optional '='

Thanks in advance for any help.

Upvotes: 1

Views: 3518

Answers (3)

dynamic
dynamic

Reputation: 48091

In this case I think it's better if you use simpler functions like explode(,'#') and/or strpos.

They are suggested for simple string manipulation like this

Upvotes: 0

anubhava
anubhava

Reputation: 785058

You didn't specify which language. In php you can do:

<?php
preg_match('~#(([^=#]*))~', $str, $m );
var_dump($m[1]); // $m[1] is your string here
?>

Upvotes: 1

Gumbo
Gumbo

Reputation: 655219

Try this regular expression:

#([^=]*)

This matches anything after # that is not a =. It doesn’t matter whether there is actually a = following or not.

Upvotes: 2

Related Questions