1

I have searched a lot for a regular expression or pattern that would work for me, but I haven't found any.

In a Edit text I want to allow first 4 digit and then 2 uppercase letters, so Ihave created a pattern:

private final Pattern sPattern  = Pattern.compile("^[0-9]{0,4}[A-Z]{0,2}");

But it allows first 2 capital letters, too.

If i change my pattern to

private final Pattern sPattern  = Pattern.compile("^[0-9]{0,4}[A-Z]{4,6}"); 

I am not able to get anything rright.

Please help me with this.

Thanks.

4
  • 1
    Do you know what {4,6} means? Commented Jul 8, 2015 at 10:12
  • I think position from and to. Commented Jul 8, 2015 at 10:41
  • @Amee: {4,6} is a limiting quantifier that matches the preceding subpattern 4, 5 or 6 times. It has nothing to do with positions in string. Commented Jul 8, 2015 at 10:44
  • @Amee Then you should probably get your hands on a regex tutorial or book, and start there. Commented Jul 8, 2015 at 10:51

1 Answer 1

1

You need to be careful with limiting quantifier. Just remove 0, as it allows less than 4 digits or 2 uppercase letters:

^[0-9]{4}[A-Z]{2}

This will require 4 digits at the beginning and 2 letters after.

See demo

For live validation, you can use

^[0-9]{0,4}(?:(?<=[0-9]{4})[A-Z]{0,2})?

It will allow a user to input 0 to 4 digits and then 0 to 2 English uppercase letters only if there are 4 digits before them. Mind that if the input can contain just these max 6 characters, you can add the $ end-of-string anchor at the end.

Sign up to request clarification or add additional context in comments.

18 Comments

Note that you cannot use 1 regex for both live input validation and final input validation. ^[0-9]{4}[A-Z]{2} is the regex to be used when the textbox loses focus (final validation). Your regex is quite fine for live validation, but you might want to check for at least 1 digit before a letter with ^[0-9]{1,4}[A-Z]{0,2}, or use a look-around to disallow only letters at the beginning: ^[0-9]{0,4}(?<=[0-9])[A-Z]{0,2}.
hello Stribizhev , This pattern allow me to add like 34AS also, I use this pattern ^[0-9]{0,4}(?<=[0-9])[A-Z]{0,2}
Sure it will. So, you want to use the regex for live validation, and the number of digits in the beginning must be exactly 4, right? And then a user should be able to type only 2 letters, right? Try ^[0-9]{0,4}(?:(?<=[0-9]{4})[A-Z]{0,2})?.
Thanks, it works now, Can u give any link or tutorial so that i can learn how to make regular expression???
You can learn a lot at regular-expressions.info, and use regexplanet or ocpsoft to quickly check simple regex patterns.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.