How to check for spaces before, in the middle and at the end of a string using Regex in C#?

Asked

Viewed 365 times

-2

I need to check with regex so that only letters and numbers are allowed. The other characters such as ,.-*&%$#@; among others cannot be accepted. In the regex below, I’m able to validate it! I’m just having problems with white spaces. In the regex below, it can validate whitespace if I type at least one letter or number. Ex: 1(space) or (space)A. The problem occurs when I type only spaces and do not type letters or numbers, the regex below does not recognize them. I need to improve the regex below, so that it validates when I type only (blanks)and not accept them, regardless of the amount.

protected void ValidarCodigoControle()
{
    RuleFor(p => p.CodigoControle)
        .NotEqual("0").WithMessage("O Código de Controle é inválido.")
        
        .MaximumLength(15).WithMessage("O Código de Controle deve ter no máximo 15 caracteres.")
        .Must(TextoHelper.NaoELetraNemNumeroNemEspaco).WithMessage("O Campo Código de Controle deve possuir apenas letras ou números.");
}


public static bool NaoELetraNemNumeroNemEspaco(string texto)
{
    var rg = new Regex(@"^[a-zA-Z0-9]+$");
    return !string.IsNullOrEmpty(texto) ? rg.Match(texto).Success : true;
}

How do I do it?

Thank you :)

  • 1

    To see if there are spaces in the beginning, middle or end, nor need regex, use Contains is enough. But if regex should allow only letters and numbers, then it will not allow spaces. So I don’t understand what you need...

  • In fact, its current regex already works, as it does not accept spaces: https://ideone.com/EhBxPK

  • @hkotsubo this regex you have problems she, IE, has differences in fact it forces be a way, finally the question ta confused a little.

  • @Virgilionovic In my comment above, the ideone link is an example in C# with the same regex as the question. And it doesn’t allow spaces, which by the comments I understood is what he wants. The only detail is that this regex requires at least one number (because of the \d+) but the issue of not accepting space already does. Anyway, I still do not understand what the question actually wants, because from what I understand the regex already works...

  • @hkotsubo True, Master JR tries to edit the question and if possible put examples of what can and cannot be accepted.

  • Try posting the place where you are validating, see that even if you have more spaces it works https://dotnetfiddle.net/1kIgHz

  • Yes @hkotsubo I understand, I’m just saying that by his question is confused understand, how complicated it is to understand what he wants, so much that there is no right answer for him ... complicated.

  • @Virgilionovic, I edited the question...

  • I believe that the problem is not the regex but where you are validating.

  • @ Wictor Keys, I am using Fluentvalidation and calling a function to validate with regex. I will post the source.

Show 5 more comments

2 answers

0


Check for space

If you just want to check if there is space is very simple, just put in the expression only space, see the example:

using System;
using System.Text.RegularExpressions;
                    
public class Program
{
    public static void Main()
    {
        var rg = new Regex(@" ");
        if(rg.IsMatch("Hello World")){
            Console.WriteLine("Tem espaço");
        }else{
            Console.WriteLine("Não tem espaço");
        }       
    }
}

Check if it is valid

Now if you want there to be no special character and no space you can make this way:

using System;
using System.Text.RegularExpressions;
                    
public class Program
{
    public static void Main()
    {
        var rg = new Regex(@"^[a-zA-Z0-9]+$");
        if(rg.IsMatch("Hello World")){
            Console.WriteLine("Certo");
        }else{
            Console.WriteLine("Errado");
        }       
    }
}

Checks if it is valid and empty

In the above example the expression does not accept empty, replacing "+" with "*" is accepted empty as well:

using System;
using System.Text.RegularExpressions;
                    
public class Program
{
    public static void Main()
    {
        var rg = new Regex(@"^[a-zA-Z0-9]*$");
        if(rg.IsMatch("Hello World")){
            Console.WriteLine("Certo");
        }else{
            Console.WriteLine("Errado");
        }       
    }
}

So he’ll accept letters and numbers only.

  • Thanks for the help @Wictor Chaves! I would like to validate, in the string, if it contains only letters, numbers and no spaces (in the beginning, middle and end). How would I do that?

  • It is this second example, but in this case it will also not accept empty, if you want to accept empty also exchange the "+" for "*" which will work with empty as well.

  • In vdd, I want it to accept only letters and numbers. It cannot contain any special character (Type -,$%#@), nor space.

  • The second example does just that. Remembering that if an empty string is accepted also you should exchange the "+" for "*".

  • I am doing with your suggestion [a-za-Z0-9]+$. It works if I enter 1 and enter space, it is validating. If I type in the string two spaces, it does not validate.

  • It only works if the space is entered at the end of the string or at the beginning... If I type only space, for example, then regex validation does not take.

Show 1 more comment

0

Basically in his regex enter what is required (numbers and letters) ^[a-zA-Z0-9]*$, example:

using System;
using System.Text.RegularExpressions;       
public class Program
{
    public static void Main()
    {
        Regex r = new Regex("^[a-zA-Z0-9]*$");                
        System.Console.WriteLine(r.IsMatch("abcAbc123"));     // true
        System.Console.WriteLine(r.IsMatch(" abcAbc123"));    // false
        System.Console.WriteLine(r.IsMatch("abcAbc123 "));    // false
        System.Console.WriteLine(r.IsMatch("abc Abc123"));    // false
        System.Console.WriteLine(r.IsMatch(" abc Abc 123 ")); // false
        System.Console.WriteLine(r.IsMatch("Ab125cAbc123"));  // true
    }
}

Online: https://dotnetfiddle.net/wV5xYb

Browser other questions tagged

You are not signed in. Login or sign up in order to post.