• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 706
  • Last Modified:

Regular expressions .matches()

Hi,

I want to make sure a user only enters alphanumeric values, _ or - into a text field, I've coded the below code but it's leaving some special characters through e.g * or ", can anyone shed some light on why these are allowed through?


        //Make sure text only has alphanumeric values or "_" and "-".
        if(TextField.getText().trim().matches("[^a-z ^A-Z ^0-9 ^_ ^-]"))
        {
                //popup and error message
        }
0
LiamOB
Asked:
LiamOB
  • 4
  • 3
1 Solution
 
CEHJCommented:
matches() has to match the *whole* string. You only specified a String of one character
0
 
CEHJCommented:
Try
boolean valid = s.matches("[\\w\\-]+");

Open in new window

0
 
LiamOBAuthor Commented:
I thought the code

 if(TextField.getText().trim().matches("[^a-z ^A-Z ^0-9 ^_ ^-]"))
{
//Show error message
}

would check if the text in the textfield is not between a-z, A-Z, 0-9 _ or - then show an error message.


Can you explain this code: I know \\w is a word character so would deal with a-z, A-z and 0-9.

boolean valid = s.matches("[\\w\\-]+");
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
CEHJCommented:
You probably meant
if(TextField.getText().trim().matches("[a-zA-Z0-9_-]+"))

Open in new window

0
 
LiamOBAuthor Commented:
So it's the negative of this that I really want, but yeah your code with the ! at the start works for me.

if(!TextField.getText().trim().matches("[a-zA-Z0-9_-]+"))

Open in new window


0
 
LiamOBAuthor Commented:
Thanks for your help.
0
 
CEHJCommented:
:)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now