How to set the first character via regex?
The first character can be anything except an equals sign (=
).
I made the following regex:
[^=].
ab
, b2
etc will pass, and =a
will not.
But the thing is, I also want to accept single character:
a
should also be accepted. How can I do that?
Update
You might wonder why I'm doing it. I have a URL regex
(?!=)((www\.|(https?开发者_Go百科|ftp)://)[.a-z0-9-]+\.[a-z0-9/_:@=.+?,#%&~-]*[^.'#!()?, ><;])
but I don't want the URL to be parsed if it's right after the =
character.
Try a negative lookahead:
^(?!=)
^
matches the start of the input, and (?!...)
is a negative look ahead. It also matches an empty string.
If this is the only constraint in your regex, you should try to use the API provided by the language you're working with to get the first character of a string.
String s = "myString";
if(s.Length == 0 || s[0] != '=')
//Your code here
If you really want a regex look at @Bart solution.
Here is an alternative without look ahead /^([^=]|$)/
^ <- Starts with
( <- Start of a group
[^=] <- Any char but =
| <- Or
$ <- End of the match
) <- End of the group
You don't need RegEx. There is String.StartsWith...
if ( ! theString.StartsWith("=") ) {
...
Anchor to the beginning and end, and make the whole thing optional.
^(?:[^=].*)?$
Couldn't you just use ^=
and act if there is no match in your code?
精彩评论