1

I want to do validation for a String which can only contains alphanumeric and only one special character. I tried with (\\W).{1,1}(\\w+).

But it is true only when I start with a special character. But I can have one special character at any place in String.

1
  • Please show examples that should be matched and others that shouldn't. Commented Jan 23, 2012 at 13:50

4 Answers 4

1

Use the ^ and $ anchors to instruct the regex engine to start matching from the beginning of the string and stop matching at the end of the string, so taking your regex:

^(\\W).{1,1}(\\w+)$

Please take a look at this Oracle (Java) tutorial on regular expressions.

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

Comments

1

Try this regexp: \w*\W?\w* (Java string: "\\w*\\W?\\w*")

This expression has a drawback of matching zero-length strings. If your input must have exactly one special character, remove the question mark ? from the expression.

Comments

0

use matcher.find() and not matcher.match() and search for \\w and remove plus (+) because it will match all alphanumeric characters sequence in your string.If your string contains only them, your regex will match whole string.

Comments

0

if I understand your regex correctly, this could solve your problem:

([\w]+)([^\w])([\w]+)

1 Comment

Its simple like i want a string which can alpha numeric and only one special character. eg. valid: abc! and invalid: abdc@y!

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.