orange
orange

Reputation: 5405

Regex matching capital characters, numbers and period

I'm trying to see if a input only contains capital letters, numbers and a period in regex. What would the regex pattern be for this in Java?

Is there any guides on how I can build this regex, even some online tools?

Also is it possible to check length of string is no more than 50 using regex?

Upvotes: 2

Views: 5153

Answers (6)

stema
stema

Reputation: 93026

This is the Unicode answer:

^[\p{Lu}\p{Nd}.]{0,50}$

From regular-expressions.info

\p{Lu} or \p{Uppercase_Letter}: an uppercase letter that has a lowercase variant.

\p{Nd} or \p{Decimal_Digit_Number}: a digit zero through nine in any script except ideographic scripts.

^ and $ is the start and the end of the string

Upvotes: 4

ggrigery
ggrigery

Reputation: 411

In response to what tools you can use, I prefer Regex Coach

Upvotes: 0

sgmorrison
sgmorrison

Reputation: 986

Regular expressions in Java have a lot in common with other languages when it comes to the simple syntax, with some predefined character classes that add more than you'd find in Perl for example. The Java API docs on Pattern show the various patterns that are supported. A friendlier introduction to regexes in Java is http://www.regular-expressions.info/java.html.

Some very quick Googling shows there are many tools online for testing Java regular expressions against input strings. Here is one.

To check for the type of input you are interested in, the following regex should work:

^[A-Z0-9.]{,50}$

Broken down, this is saying:

^: start matching from the start of the input; do not allow the first character(s) to be skipped

[]: match one of the characters in this range

A-Z: within a range, - means to accept all values between the first and last character inclusive, so in this case all characters from A to Z.

0-9: add to the previous range all digits

.: periods are special in regexes, but all special characters become simple again within a character class ([])

{,50}: require (or 0) matches up to 50 of the character class just defined.

$: the match must reach the end of the input; do not allow the last character(s) to be skipped

Upvotes: 1

Leesrus
Leesrus

Reputation: 1115

This website is really handy for building and testing and regular expressions

Upvotes: 1

Stanley F.
Stanley F.

Reputation: 1973

This returns true for strings, containing only 50 characters that can be numbers, capital letters or a dot.

string.matches("[0-9A-Z\\.]{0,50}")

Upvotes: 0

Etienne Perot
Etienne Perot

Reputation: 4882

Regex pattern:

Pattern.compile("^[A-Z\\d.]*$")

To check the length of a string:

Pattern.compile("^.{0,50}$")

Both combined:

Pattern.compile("^[A-Z\\d.]{0,50}$")

Although I wouldn't use regular expressions to check for length if I were you, just call .length() on the string.

Upvotes: 3

Related Questions