Regexp with only one letter

Asked

Viewed 139 times

1

I wanted to make a RegExp more or less like this 0000-x, that was available only the letter X and numbers from 0 to 9. I did a search on the net, I could only do with numbers or that took all letters.

Here’s an example I did, just with numbers: http://jsfiddle.net/1pmwau62/

  • X you want it to be a number ?

  • Not, x would be the only letter that could be put into the input

  • 0000-A would be a valid entry, right ?

1 answer

3


Just use a set:

[xX\d] para 0 a 9 OU x
[0-9xX] para 0 a 9 OU x
[xX] para SOMENTE x

Applying to your case:

v=v.replace(/^(\d{4})([0-9x])/g,"$1-$2");


When you use sets in Regexp, is saying "any of these characters". Examples:

[a-zA-Z0-9] Qualquer letra minúscula ou maiúscula, ou os dígitos de 0 a 9
[abcdABCD]{2} Qualquer combinação de 2 caracteres como aB, DD, Da, db, etc
  • But I could still put other letters, the difference is with the x the mask works

  • 1

    @Altembergandrade I’m answering about regexp now, it may be that your mask function has some problem, which is a completely different question.

  • I tested its function here, and it formats the data correctly. What happens is that its function is not a typing mask, but a formatting mask. It applies the mask when typed corresponds to regex. If you want to filter what was typed, you need to review the whole function.

  • Yeah, I got it @Bacco. I had these doubts there of Regexp rsrs. I’ll try to make it accept only the letter X. Vlw ^^

  • @Altembergandrade take a look at these questions, maybe something will help (there you use the format I commented on the answer): http://answall.com/search?q=máscara+%5Bjavascript%5D

  • [0-9]{4}[xX] would be the most appropriate in this way

  • @Marcelobonifazio in the statement he says it can be X or 0 to 9 (although in the comment he says something else, then it gets complicated :) ). Qq way, the problem is another, is in the filter function. I don’t even know if it’s the closing case.

  • @Marcelobonifazio in doubt updated the answer with the 2 cases in the beginning.

Show 3 more comments

Browser other questions tagged

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