tags:

views:

60

answers:

6

The first character can be anything except '='.

I made the following RegEx:

[^=].

"ab", "b2" etc will pass. "=a" will not.

But the thing is, I also want to accept an empty character:

"a" should also be accepted. How can I do that?

Update

Sorry, the language is C#

You might wonder why I'm doing it. I have a URL RegEx

(?!=)((www.|(http|https|ftp)\://)[.a-z0-9-]+.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|# |!|(|?|,| |>|<|;|)])

but I don't want the URL to be parsed if it's right after the '=' character.

+5  A: 

Try a negative lookahead:

^(?!=)

^ matches the start of the input, and (?!...) is a negative look ahead. It also matches an empty string.

Bart Kiers
How do you know that it is a perl regex that is needed here? :)
Benoit
@Benoit, it is a PCRE syntax, so not only supported by Perl. PHP, Java, JavaScript, Python, etc. all support the syntax I posted above.
Bart Kiers
I think that's almost what I need. However, "^(?!=)aa" doesn't accept " aa", and I need spaces to be accepted too. So I think that "^" should not be in the RegEx. You might wonder why I'm doing it. I have a URL RegEx, but I don't want the URL to be parsed if it's right after the '=' character.
Alex
@Alex, `^(?!=)aa` only matches strings that start with `aa` (the look ahead isn't even needed in that case). I don't understand why you'd add the `aa` in your regex.
Bart Kiers
Ok, I solved the problem by modifying your solution a little. Thank you!
Alex
@Alex, ah, good to hear that. You're welcome.
Bart Kiers
A: 

Anchor to the beginning and end, and make the whole thing optional.

^(?:[^=].*)?$
Ignacio Vazquez-Abrams
A: 

Couldn't you just use ^= and act if there is no match in your code?

Benoit
A: 

Try using this one:

^[^=].*
bazmegakapa
Won't match empty string.
KennyTM
Yeah, you're right...
bazmegakapa
+3  A: 

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
Colin Hebert
+1  A: 

You don't need RegEx. There is String.StartsWith...

if ( ! theString.StartsWith("=") ) {
   ...
KennyTM