简体   繁体   中英

insert string that match regular expression

My program takes a string input from a user. If the input string matches the regular expression then it should be inserted into the arrayList.

I wrote that following. But, it does not work:

        if( element.matches("[a-zA-Z]"));
        {
        set.add(element);
        }

If that's actually how your code is written then the element will always be added to the set . You need to remove the ; at the end of the first line for the conditional to work:

if (element.matches("[a-zA-Z]")) {
    set.add(element);
}

If you're trying to match more than more character you likely want "[a-zA-Z]+" for the expression.

I guess you forgot the + sign, meaning "once or more":

if (element.matches("[a-zA-Z]+")) {..}

(and of course, as the example above shows, you have to get rid of the semicolon)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM