0

I need a regular expression that matches a String at the beginning of the input which satisfies following conditions:

  1. start with a letter
  2. end with a letter or a number
  3. may contain letters, numbers and spaces

I have this expression so far:

^([a-zA-Z]+[a-zA-Z0-9 ]*[a-zA-Z0-9]+)|[a-zA-Z]

http://userguide.icu-project.org/strings/regexp

The OR statement in the expression is to allow a String that consists of one letter.

The problem is that the second part of the OR statement is always preferred, so when the input is query1, it matches only q.

How can I solve this problem?

Is there a way to simplify the expression? My way seems a little to complex for this relatively simple case.

3 Answers 3

1
^([a-zA-Z]+[a-zA-Z0-9 ]*[a-zA-Z0-9]+)$|^[a-zA-Z]$

You can make use of ^$ anchors to imply that that it is only for single letter string

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

Comments

1

You can use this regex to satisfy all conditions:

^[a-zA-Z](?:[a-zA-Z0-9 ]*[a-zA-Z0-9])?$
  • ^[a-zA-Z] matches a letter at start.
  • (?:...)? is optional part to allow single char input.
  • [a-zA-Z0-9] in the makes sure last char is alpha-numeric.

RegEx Demo

Comments

0

Regex to match with a character at the start, character, number or spaces in between and ends with character or number:

^[a-z|A-Z][a-z|A-Z|0-9| ]*[a-z|A-Z|0-9]$

Comments

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.