CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jun 2008
    Posts
    61

    Arrow Trying to master Regular expression :->

    Hi, I want the input to accept only: digits, operators and space. How could I do?
    I mean:

    When I type: 8 – 9 a b c ! ?
    It should throw exception.

    When I type: 8 – 9 + 20 * 1 / 5
    It should end in success.

    I tried but could not
    Code:
    package assignments;
    
    import java.util.Scanner;
    
    public class RegexTest {
    
    	public static void main(String[] args) {
    
    		Scanner scanner = new Scanner(System.in);
    		String s = scanner.next();
    		
    		// try to input: 8 - 9 + 20 * 1 /   5		
    		try {
    			if(s.matches("[^ \\d \\+ \\- \\* \\/]+"))
    				throw new Exception();
    		} catch (Exception e) {			
    			System.err.println("Recycle bin: \"I\'m here\"");
    		}					
    	}
    }

  2. #2
    Join Date
    Apr 2009
    Location
    TR
    Posts
    97

    Re: Trying to master Regular expression :->

    define an array and give operators which u want as value..get input and compare it array' s values..and use if for digits and space..

    Please use code tags like this :
    [SIGPIC][/SIGPIC]
    Code Your Dreams

  3. #3
    Join Date
    Jun 2008
    Posts
    61

    Re: Trying to master Regular expression :->

    I'm sorry but I'd like to use regex. Read the topic tittle la. =__=
    I think it's ok if I use regex in this case. (shorter and more professional I think)

  4. #4
    Join Date
    May 2009
    Location
    Lincs, UK
    Posts
    298

    Re: Trying to master Regular expression :->

    Do it the other way round, instead of throwing the exception when the input matches that regex do it when the input does not match, but using this other regex (without the ^):
    Code:
    [\\d\\+\\-\\*\\/ ]+

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured