Regex to check only capital letters, two special characters (& and Ñ) & without any space between

16,747

Solution 1

This is happening because you have a negation(^) inside the character class.

What you want is: ^[A-Z0-9&Ñ]+$ or ^[A-Z\d&Ñ]+$

Changes made:

  • [0-9] is same as \d. So use either of them, not both, although it's not incorrect to use both, it's redundant.
  • Added start anchor (^) and end anchor($) to match the entire string not part of it.
  • Added a quantifier +, as the character class matches a single character.

Solution 2

^[A-Z\d&Ñ]+$

0-9 not required.

Solution 3

if you want valid patterns, then you should remove the ^ in the character range.

[A-Z0-9\d&Ñ]

Share:
16,747
Biki
Author by

Biki

Hi, Am Bikash, currently with Dell Bangalore. Earlier I was with Advice America, followed by Ness Technologies. I deal with Microsoft Technologies, primarily in to C# Development in ASP.Net MVC framework. I have personal interest in Finance Domain & often do some analysis in this field.

Updated on June 17, 2022

Comments

  • Biki
    Biki almost 2 years

    I am using below code snippet to validate my input string with: only capital letters, numbers and two special characters (those are & and Ñ) & without any space between.

    var validpattern = new RegExp('[^A-Z0-9\d&Ñ]');
    if (enteredID.match(validpattern))
       isvalidChars = true;
    else
       isvalidChars = false;
    

    Test 1: "XAXX0101%&&$#" should fail i.e isvalidChars = false; (as it contains invalid characters like %$#.

    Test 2: "XAXX0101&Ñ3Ñ&" should pass.

    Test 3: "XA 87B" should fail as it contains space in between

    The above code is not working, Can any one help me rectifying the above regex.

    • Gumbo
      Gumbo over 13 years
      What about your previous question?
    • Ikaso
      Ikaso over 13 years
      Maybe you should remove the negation ^.
  • Biki
    Biki over 13 years
    Thanks for the explanation, but let me know which part of the regex is responsible for checking the spaces?
  • codaddict
    codaddict over 13 years
    @Biki: We are allowing only upper case letters, digits and the two special char. So this automatically does not allow any other characters like the space.
  • Biki
    Biki over 13 years
    Ya, Very true. Using jquery we could achieve the same in one line: $('#txtFederalTaxId').alphanumeric({ allow: " &Ñ" });
  • Simon Dell
    Simon Dell over 6 years
    This "in one line" thing isn't a useful metric of "good code". Often a higher count of shorter lines gives your readers better understanding of your intent (and more scope to refactor later). However... if you want a "pure JS" one-liner, try something based on: isvalidChars = /^[A-Z0-9&Ñ]+$/.test(enteredID). This works because JS supports RegEx literals.