Pattern and Matcher problem. Help Please!

I am trying to make the user enter a correct US$ in HTML(jsp format) ie 12.34 but not 12.3456. As far as i know, the regular expression below is correct for $$.
but the there is no error even if the user types 12.34567
can anyone help me please?
this is the code i wrote...
public static final int DATA_ENTRY = 1;
public static final int INVALID_CURRENCY = 2;
public static final int PROCESS_INPUT = 3;
int state;
String a; //data input from user
Pattern p = Pattern.compile("\\d{1,3}(?:(?:,\\d\\d\\d)*|\\d*)(?:\\.\\d\\d)?");
Matcher m = p.matcher(a);
state = DATA_ENTRY; // this is default
if (m.find() {
     state = PROCESS_INPUT;
else {
     state = INVALID_CURRENCY;

Here's two pattern strings that both require a two-place fraction for each entry but do not permit more than two places.
import java.util.regex.*;
public class snggun {
  public static void main(String[] args) {
    String input = (args.length > 0 ? args[0] : "10.00");
//    String mask = "\\d{1,3}(?:(?:,\\d\\d\\d)*|\\d*)(?:\\.\\d\\d)?";
    // requires two-place fraction
//    String mask = "^(\\d{1,3})(,(\\d\\d\\d))*(\\.\\d\\d)\\z";
    // requires two-place fraction
    String mask = "\\d{1,3}(?:(?:,\\d{3})*|\\d*)(\\.\\d{2})\\z";
    Pattern pattern = Pattern.compile(mask);
    Matcher match = pattern.matcher(input);
    System.out.println("input = " + input + " qualifies " + match.find());
    if(match.find())
      for(int j = 0; j <= match.groupCount(); j++)
        System.out.println("group " + j + "  " + match.group(j));
}

Similar Messages

  • Iphone and email problems - help please!

    I have a few questions about email on the iphone I wondered if someone could help me with?
    1. If I check my email at home on wifi everything is fine, I can recieve and send emails no problem. If I am outside and using GPRS ( Not found an EDGE signal yet ) I can recieve emails but when I try and send one it tells me it cannot find the outgoing server after trying to send the email for a few minutes.
    2. Sometimes I open my email and its fine but when I go back and try and open an email I have previously read it says "This message has not been dowloaded from the server". How do I get the email to stay there?
    Thanks guys

    See my reply on this post.
    http://discussions.apple.com/message.jspa?messageID=5842248#5842248
    In sort, even once you view it, it will not remain in the Inbox for ever...it will attempt to redownload if accessed later.

  • How to Use Pattern and Matcher class.

    HI Guys,
    I am just trying to use Pattern and Matcher classes for my requirement.
    My requirement is :- It should allow the numbers from 1-7 followed by a comma(,) again followed by the numbers from
    1-7. For example:- 1,2,3,4,5 or 3,6,1 or 7,1,3 something like that.
    But it should not allow 0,8 and 9. And also it should not allow any Alphabets and special characters except comma(,).
    I have written some thing like..
    Pattern p = Pattern.compile("([1-7])+([\\,])?([1-7])?");
    Is there any problem with this pattern ??
    Please help out..
    I am new to pattern matching concept..
    Thanks and regards
    Sudheer

    ok guys, this is how my code looks like..
    class  PatternTest
         public static void main(String[] args)
              System.out.println("Hello World!");
              String input = args[0];
              Pattern p = Pattern.compile("([1-7]{1},?)+");
              Matcher m = p.matcher(input);
              if(m.find()) {
                   System.out.println("Pattern Found");
              } else {
                   System.out.println("Invalid pattern");
    }if I enter 8,1,3 its accepting and saying Pattern Found..
    Please correct me if I am wrong.
    Actually this is the test code I am presenting here.. I original requirement is..I will be uploading an excel sheets containg 10 columns and n rows.
    In one of my column, I need to test whether the data in that column is between 1-7 or not..If I get a value consisting of numbers other than 1-7..Then I should
    display him the msg..
    Thanks and regards
    Sudheer

  • Pattern and Matcher of Regular Expressions

    Hello All,
    MTMISRVLGLIRDQAISTTFGANAVTDAFWVAFRIPNFLRRLFAEGSFATAFVPVFTEVK
    ETRPHADLRELMARVSGTLGGMLLLITALGLIFTPQLAAVFSDGAATNPEKYGLLVDLLR
    LTFPFLLFVSLTALAGGALNSFQRFAIPALTPVILNLCMIAGALWLAPRLEVPILALGWA
    VLVAGALQLLFQLPALKGIDLLTLPRWGWNHPDVRKVLTLMIPTLFGSSIAQINLMLDTV
    IAARLADGSQSWLSLADRFLELPLGVFGVALGTVILPALARHHVKTDRSAFSGALDWGFR
    TTLLIAMPAMLGLLLLAEPLVATLFQYRQFTAFDTRMTAMSVYGLSFGLPAYAMLKVLLP
    I need some help with the regular expressions in java.
    I have encountered a problem on how to retrieve two strings with Pattern and Matcher.
    I have written this code to match one substring"MTMISRVLGLIRDQ", but I want to match multiple substrings in a string.
    Pattern findstring = Pattern.compile("MTMISRVLGLIRDQ");
    Matcher m = findstring.matcher(S);
    while (m.find())
    outputStream.println("Selected Sequence \"" + m.group() +
    "\" starting at index " + m.start() +
    " and ending at index " m.end() ".");
    Any help would be appreciated.

    Double post: http://forum.java.sun.com/thread.jspa?threadID=726158&tstart=0

  • Pattern and Matching question

    Hey,
    I'm trying to use the pattern and matcher to replace all instances of a website
    address in some html documents as I process them and post them. I'm
    including a sample of some of the HTML below and the code I"m using to
    process it. For some reason it doesn't replace the sites in the underlying
    images and i can't figure out what I'm doing wrong. Please forgive all the
    unused variables, those are relics of another way i may have to do this if i
    can't get the pattern thing to work.
    Josh
         public static void setParameters(File fileName)
              FileReader theReader = null;
              try
                   System.out.println("beginning setparameters guide2)");
                   File fileForProcessing=new File(fileName.getAbsolutePath());
                   //wrap the file in a filereader and buffered reader for maximum processing
                   theReader=new FileReader(fileForProcessing);
                   BufferedReader bufferedReader=new BufferedReader(theReader);
                   //fill in data into the tempquestion variable to be populated
                   //Set the question and answer texts back to default
                   questionText="";
                   answerText="";
                   //Define the question variable as a Stringbuffer so new data can be appended to it
                   StringBuffer endQuestion=new StringBuffer();//Stringbuffer to store all the lines
                   String tempQuestion="";
                   //Define new file with the absolutepath and the filename for use in parsing out question/answer data
                   tempQuestion=bufferedReader.readLine();//reads the nextline of the question
                   String tempAlteredQuestion="";//for temporary alteration of the nextline
                   //while there are more lines append the stringbuffer with the new data to complete the question buffer
                   StringTokenizer tokenizer=new StringTokenizer(tempQuestion, " ");//tokenizer for reading individual words
                   StringBuffer temporaryLine; //reinstantiate temporary line holder each iterration
                   String newToken;   //newToken gets the very next token every iterration?  changed to tokenizer moretokens loop
                   String newTokenTemp;   //reset newTokenTemp to null each iterration
                   String theEndOfIt;  //string to hold everything after .com
                   char[] characters;  //character array to hold the characters that are used to hold the entire link
                   char lastCharChecked;
                   Pattern thePattern=Pattern.compile("src=\"https:////fakesite.com//ics", Pattern.LITERAL);
                   Matcher theMatcher=thePattern.matcher(tempQuestion);
                        while(tempQuestion!=null) //every time the tempquestion reads a newline, make sure you aren't at the end
                             String theReplacedString=theMatcher.replaceAll("https:////fakesite.com//UserGuide/");     
                             //          temporaryLine=new StringBuffer();
                             //add the temporary line after processed back into the end question.
                             endQuestion.append(theReplacedString);                              //temporaryLine.toString());
                             //reset the tempquestion to the newline that is going to be read
                             tempQuestion=bufferedReader.readLine();
                             if(tempQuestion!=null)
                                  theMatcher.reset(tempQuestion);
                             /*newTokenTemp=null;
                             while(tokenizer.hasMoreTokens())
                                  newToken=tokenizer.nextToken(); //get the next token from the line for processing
                                  System.out.println("uhhhhhh");
                                  if(newToken.length()>36)  //if the token is long enough chop it off to compare
                                       newTokenTemp=newToken.substring(0, 36);
                                  if(newTokenTemp.equals("src=\"https://fakesite.com"));//compare against the known image source
                                       theEndOfIt=new String();  //intialize theEndOfIt
                                       characters=new char[newToken.length()];  //set the arraylength to the length of the initial token
                                       characters=newToken.toCharArray();  //point the character array to the actual characters for newToken
                                       lastCharChecked='a';  // the last character that was compared
                                       int x=0; //setup the iterration variable and go from the length of the whole token back till you find the first /
                                       for(x=newToken.length()-1;x>0&&lastCharChecked!='/';x--)
                                            System.out.println(newToken);
                                            //set last char checked to the lsat iterration run
                                            lastCharChecked=characters[x];
                                            //set the end of it to the last char checked and the rest of the chars checked combined
                                            theEndOfIt=Character.toString(lastCharChecked)+theEndOfIt;
                                       //reset the initial newToken value to the cut temporary newToken root + userguide addin, + the end
                                       newToken=newTokenTemp+"//Userguide"+theEndOfIt;
                                  //add in the space aftr the token to the temporary line and the new token, this is where it should be parsed back together
                                  temporaryLine.append(newToken+" ");
                             //add the temporary line after processed back into the end question.
                             endQuestion.append(temporaryLine.toString());
                             //reset the tempquestion to the newline that is going to be read
                             tempQuestion=bufferedReader.readLine();
                             //reset tokenizer to the new temporary question
                             if(tempQuestion!=null)
                             tokenizer=new StringTokenizer(tempQuestion);
                   //Set the answer to the stringbuffer after converting to string
                   answerText=endQuestion.toString();
                   //code to take the filename and replace _ with a space and put that in the question text
                   char theSpace=' ';
                   char theUnderline='_';
                   questionText=(fileName.getName()).replace(theUnderline, theSpace);
              catch(FileNotFoundException exception)
                   if(logger.isLoggable(Level.WARNING))
                   logger.log(Level.WARNING,"The File was Not Found\n"+exception.getMessage()+"\n"+exception.getStackTrace(),exception);
              catch(IOException exception)
                   if(logger.isLoggable(Level.SEVERE))
                   logger.log(Level.SEVERE,exception.getMessage()+"\n"+exception.getStackTrace(),exception);
              finally
                   try
                        if(theReader!=null)
                             theReader.close();
                   catch(Exception e)
    <SCRIPT language=JavaScript1.2 type=text/javascript><!-- if( typeof( kadovInitEffects ) != 'function' ) kadovInitEffects = new Function();if( typeof( kadovInitTrigger ) != 'function' ) kadovInitTrigger = new Function();if( typeof( kadovFilePopupInit ) != 'function' ) kadovFilePopupInit = new Function();if( typeof( kadovTextPopupInit ) != 'function' ) kadovTextPopupInit = new Function(); //--></SCRIPT>
    <H1><IMG class=img_whs1 height=63 src="https://fakesite.com/ics/header4.jpg" width=816 border=0 x-maintain-ratio="TRUE"></H1>
    <H1>Associate Existing Customers</H1>
    <P>blahalbalhblabhlab blabhalha blabahbablablabhlablhalhab.<SPAN style="FONT-WEIGHT: bold"><B><IMG class=img_whs2 height=18 alt="Submit a

    If you use just / it misinterprets it and it ruins
    your " " tags for a string. I don't think so. '/' is not a special character for Java regex, nor for Java String.
    The reason i used
    literal is to try to force it to directly match,
    originally i thought that was the reason it wasn't
    working.That will be no problem because it enforces '.' to be treated as a dot, not as a regex 'any character'.
    Message was edited by:
    hiwa

  • String.matches vs Pattern and Matcher object

    Hi,
    I was trying to match some regex using String.matches but for me it is not working (probably I am not using it the way it should be used).
    Here is a simple example:
    /* This does not work */
    String patternStr = "a";
    String inputStr = "abc";
    if(inputStr.matches( "a" ))
    System.out.println("String matched");
    /* This works */
    Pattern p = Pattern.compile( "a" );
    Matcher m = p.matcher( "abc" );
    boolean found = false;
    while(m.find())
    System.out.println("Matched using Pattern and Matcher");
    found = true;
    if(!found)
    System.out.println("Not matching with Pattern and Matcher");
    Am I not matches method of String class properly?
    Please throw some lights on this.
    Thank you.

    String.matches looks at the whole string.
    bsh % "abc".matches("a");
    <false>
    bsh % "abc".matches("a.*");
    <true>

  • Searching and Matching - Difference between 'Match Pattern' and 'Match Geometric Pattern'?

    I was wondering if someone can explain to me the difference between  'Match Pattern' and 'Match Geometric Pattern' VIs? I'm really not sure which best to use for my application. I'm trying to search/match small spherical particles in a grey video in order to track their speed (I'm doing this after subtracting two subsequent frames to get rid of background motion artifacts).
    Which should I use?
    Thank you!
    Solved!
    Go to Solution.

    Hi TKassis,
    1.You may find from this link for the difference between these two,
    Pattern Match : http://zone.ni.com/reference/en-XX/help/370281P-01/imaqvision/imaq_match_pattern_3/
    Geometric Match : http://zone.ni.com/reference/en-XX/help/370281P-01/imaqvision/imaq_match_geometric_pattern/.
    2. I always prefer match pattern because of its execution speed, and incase of geometric pattern match it took lot of time to match your result. You may find in the attached figure for same image with these two algorithm execution time.
    Sasi.
    Certified LabVIEW Associate Developer
    If you can DREAM it, You can DO it - Walt Disney

  • All of my playlists made on my Ipod touch 3rd gen keep disappearing when I sync it to itunes. Drivng me crazy. All software up to date on both itunes and Ipod. Help please.

    All of my playlists made on my Ipod touch 3rd gen keep disappearing when I sync it to itunes. Drivng me crazy. All software up to date on both itunes and Ipod. Help please.
    I tend to make my playlists right on my ipod. This did not happen for the last 2 years. Just started recently. Did get a new computer recently.

    That is because you got a new computer. You can only sync all media from one syncing computer. You can sync from any computer to iPod using the manual method but that does not sync from iPod to computer.
    To make this your syncing computer:
    Syncing to a "New" Computer or replacing a "crashed" Hard Drive: Apple Support Communities

  • £37 has disappeared from my iTunes account. But no apps or music or tv/movies have been bought. Has it been hacked and can you help please?

    £37 has disappeared from my iTunes account. But no apps or music or tv/movies have been bought. Has it been hacked and can you help please?

    Report it to Apple:
    How to report an issue with your iTunes Store purchase - http://support.apple.com/kb/HT1933 - working through iTunes application and iTunes Store interface.
    iTunes Customer Service Contact - http://www.apple.com/support/itunes/contact.html
    Change the password on your account.

  • Patterns and Matcher.find()

    I would be really grateful for some assistance on this. I have been at this for three hours and can't get it correct.
    I have a string such as this: "Hello this is a great <!-- @@[IMAGINE_SPACIAL_VECTOR]@@ --> little string"
    I want to use RegEx, Pattern and Matcher.find() to extract "IMAGINE_SPACIAL_VECTOR" ie. the text between "<!-- @@[" and "]@@ -->"
    Thanks in advance for your help

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class Example {
         public static void main(String[] args) {
              String data = "Hello this is a great <!-- @@[IMAGINE_SPACIAL_VECTOR]@@ --> little string";
              Matcher matcher = Pattern.compile("<!-- @@\\[(.*?)]@@ -->").matcher(data);
              while (matcher.find()) {
                   System.out.println(matcher.group(1));
    }Might not be the best way, but it works.
    Kaj

  • HT1923 Hi, I have a iPod touch 4th generation and I does not show in iTunes. It comes up as charging when it is plugged into the computer but just not in iTunes. I have everything up to date and have restarted both computer and iPod. Help please?

    Hi, I have a iPod touch 4th generation. It comes up as charging when it is plugged into the computer but it does not show in iTunes. I have everything up to date and have restarted both computer and iPod. Help please?

    Try here  >   - http://support.apple.com/kb/TS1369.

  • My volume control is disabled after plugging in and unplugging headphones, Help Please...

    Dear all, this is my issue, I have since the beginning (October 2014) with my iPhone 5S, 64GB: My volume control is disabled after plugging in and unplugging headphones, Help Please...

    This should not happen if you have the output volume in System Prefs/Sound set low. Have you tried setting the ITunes player volume at top left a bit lower?

  • Lexical search using Pattern and Matcher class

    Hi Folks,
    Need some help with the following Query. I want to find out how I can implement
    the following by using Pattern / Matcher classes.
    I have a query that returns the following set of strings,
    aa
    abc
    def
    ghi
    glk
    gmonalaks
    golskalskdkdkd
    lkaldkdldldkdld
    mladlad
    n33ieler
    What I would like do is to find out any string that starts with g and Lexical occurs after ghi. So this will return
    ghi / glk / gmonalaks / golskalskdkdkd
    How can I accomplish the above, by using the following two classes.
    Pattern datePattern = Pattern.compile();
    Matcher dateMatcher = datePattern.matcher();
    Thanks a bunch...
    _Shoe Maker..                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Nothing in your specification requires a regex. Loop though the strings until you find the string "ghi". Then continue looping though the strings outputting those where the first characters is 'g' .

  • VIRUS PROBLEMS, HELP PLEASE???

    I continue to have messages popping up saying my computer is infected. It wants me to cleanup and I have to register with Mac Shield 2.6.  Pronograhic websites keep popping up.  Anyone having this problem?  Did not have this problem yesterday, but it's here today!  There is also a Red Sheild on the top of the toolbar where it shows the time, battery life, etc.  Right clicking on the sheild drops down Scan Now, Cleanup, Control Center, Scan, System Info, Settings, About, and Register.  A pron site just popped up again!  Need help Please!!

    Fuony wrote:
    The Mac Shield malware can come through Firefox too if you allow it to and you click on it!
    Your exactly right, it is possible that if you visit a site and need the scripts to run for something that the malware that uses Javascript is on that site, then your going to be presented with it.
    The thing is with the Firefox + NoScript combination defeats alot of the web side trickery the malware authors are using to get the malware to appear in the first place.
    Also this "MacDefender" isn't the only malware making the rounds. There are some serious Flash vulnerabilities being hosted on hostile/adult websites that are running scripts for no apparent reason other than to try to infect your machine.
    By running all scripts all the time, your computer is in a state as if you tried running across a busy highway blindfolded.
    As a lifelong "MacHead" I can understand Apple loyalty, but if Apple isn't cutting the mustard on their browser security, rather place their users security at serious risk for the sake of convenience, then I have to think about using and recommending to others something else that is more secure.
    As a example, I surf thousands of web pages a day, some on really nasty sites, yet I haven't seen this "MacDefender" appear on my computer. Even when I purposely visited links that people have submitted that had the malware. (I maintain a couple of bootable clones of my boot drive just in case)

  • ICloud problems help please!

    I have an iPhone 6 and during the setup I must have did something wrong and now I have my old iCloud account on it that I no longer remember the password, security questions, and no longer have the email address to that account.  I think I was hacked and my password and security questions changed. I want to log out of iCloud and start using my current iCloud account.  I know these are security measures, but how can I get logged out??? My iPhone is having problems since the latest update and now I can't make a call or text.  I can't call apple support without a working number  HELP Please.

    Hello shelbyrecords,
    Oh no! That sounds really frustrating. Unfortunately, if iCloud Find my iPhone Activation Lock is enabled on the device we’ll need to gain access to your previous Apple ID account to disable it. Based on the information you have provided, it sounds like you may need a personalized support experience to recover your previous Apple ID:
    If you forgot your Apple ID password - Apple Support
    http://support.apple.com/en-us/HT201487
    Make sure that you’re entering the correct Apple ID. In most cases, your Apple ID is also the primary email address of your Apple ID account. If these steps didn't help you change your password, contact Apple Support.
    Thanks,
    Matt M.

Maybe you are looking for

  • Error during database load in ECC 5.0

    Hello All, i am trying to install ECC.5 with oracle 10g during database load phase he is giving me a error when i saw in log file i found this. C:\usr\sap\EPT\SYS\exe\run/R3load.exe: START OF LOG: 20090611085559 C:\usr\sap\EPT\SYS\exe\run/R3load.exe:

  • Can I run window 8.1 pro on hp a450n

    Can I run window 8.1 pro on hp a450n with upgrade 2gb ram.

  • How we can get an interactive report  in alv grid display?

    Hi experts Plz tell me how we can get an interactive report in alv grid disply pls send me one sample code to understand this thanks in advance

  • Linksys and Laptop

    Anybody know why my Linksys WRT54GS won't connect wirelessly with my laptop (PowerBook G4 1 GHz Power PC from like 2001 running on 10.2.8) the router connects fine with my two 2.16 GHz Intel Core 2 Duo but not with this. Any advice would be great!

  • Nokia N8 frozen

    Can someone pls help. My Nokia N8 is frozen. Nothing works! I had someone call me and now the phone is ringing non stop! Unable to answer, unable to reduce volume, unable to switch the device off!