Results 1 to 4 of 4

Thread: Simple Regex

  1. #1
    Dan0100 is offline Member
    Join Date
    Aug 2010
    Posts
    18
    Rep Power
    0

    Default Simple Regex

    Hi,
    I'm really sorry to ask this question but I just can't work it out.

    How do I check if a string contains only: numbers '0-9', spaces ' ', hyphens '-', dots '.'
    If it contains any other character it will return false;

    I have this at the moment:
    Java Code:
    msg.matches("[0-9\\.\\w\\-]");
    Suffice to say.. it doesn't work :P

    Thanks for everyones help :)
    Dan

  2. #2
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    There's two issues with that:

    Firstly, \w behaves weirdly. I'm not sure of its mechanics, but just replace it with a space.

    Second, you need to account for multiple matches, with a + sign.

    Your result should be:
    "[0-9\\.\\- ]+"

  3. #3
    Dan0100 is offline Member
    Join Date
    Aug 2010
    Posts
    18
    Rep Power
    0

    Default

    Zack thank you so much.

    The "+" was what I was looking for I think :) I didn't get the multiple matches business lol.

    This forum is fantastic. Thank you again.

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is online now Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,237
    Rep Power
    19

    Default

    Another way, which should be more efficient (not tested) is attempt to find the negation of the acceptable characters. Not found [!matcher.find()] is a pass of your conditions. The regex would be
    Java Code:
    [^0-9. -]
    Note that the dot [.] is not a metacharacter when within a character class, and a dash/hyphen [-] has no special interpretation at the beginning or end of a character class, so neither of them need to be escaped.

    That said, it's sometimes wise to retain unnecessary escapes to make the regex more readable to someone less familiar with these nuances ;)
    Java Code:
    [^0-9\\.\\s\\-]
    db

Similar Threads

  1. Using Regex
    By ron87 in forum New To Java
    Replies: 4
    Last Post: 09-12-2010, 06:26 AM
  2. Please Help - Regex
    By BeeGee in forum Advanced Java
    Replies: 0
    Last Post: 04-28-2010, 05:28 PM
  3. Help with regex
    By SteroidalPsycho in forum New To Java
    Replies: 2
    Last Post: 03-29-2010, 12:40 AM
  4. Using regex
    By SteroidalPsycho in forum New To Java
    Replies: 0
    Last Post: 03-28-2010, 11:07 PM
  5. [SOLVED] More RegEx help
    By JT4NK3D in forum New To Java
    Replies: 2
    Last Post: 05-23-2008, 04:07 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •