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

Similar Messages

  • 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' .

  • Regular expressions, using pattern and matcher but not include the pattern

    Hi all
    i have a regular expression but in my matcher it is including the text that is in my regular expression.
    ie
    String str="-------------------stuff===========";
    Pattern mainBody = Pattern.compile("-----(.*?)=====", Pattern.MULTILINE);this matches -------------------stuff=====
    now i expect to get some - in there as i match from the start, but i dont want to have the = in the match. how do i do a match that excludes the matching expressions.

    nevermind, figured it out
    when i do myMatch.group(1) it gives me just my match
    sorry for wasting time :)

  • How to use interface and abstract class in the real time sennario ?

    how to validate password and reenter password fields in the struts through the xml files?

    Here is a modified dealForm.jsp that merges the 2 steps - both symbol submission and Yahoo convert is done by it. Play with it and add your DB code to it:
    <html>
    <head><title>IPIB Database Selection</title></head>
    <body bgcolor="#DFDFFF">
    <H1><CENTER>IPIB Database Selection</CENTER></H1>
    <font size=4>
    <%@ page language="java" %>
    <%@ page import="java.net.*,java.io.*,java.util.*" %>
    <%
    String symbol = request.getParameter("symbol");
    if (symbol != null) {
    String urlString = "http://finance.yahoo.com/download/javasoft.beans?SYMBOLS=" + symbol + "&format=ab";
    try {
    URL url = new URL(urlString);
    URLConnection con = url.openConnection();
    InputStream is = con.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line = br.readLine();
    StringTokenizer tokenizer = new StringTokenizer(line,",");
    String name = tokenizer.nextToken();
    name = name.substring(1, name.length()-2);
    String price = tokenizer.nextToken();
    price = price.substring(1, price.length()-2);
    %>
    <p>
    Original line from yahoo <%= line %>
    </p> <p>
    Name: <%= name %>
    </p> <p>
    Price: <%= price %>
    </p> <p>
    Pub DB processing code from dealLoad.jsp here
    </p>
    <%
    } catch (IOException exception) {
    System.err.println("IOException: " + exception);
    } else { %>
    <form action="dealForm.jsp"method="GET">
    <p>Enter Symbol: <input size="20" name="symbol">
    <inputtype="submit" value="Submit">
    </p></form>
    <% } %>
    </font>
    </body>
    </html>

  • How to use regular expression using pattern and match concept for this scenario?

    Hi Guys,
    I have a string "We have 7 tutorials for Java, 2 tutorials for Javascript and 1 tutorial for Oracle"
    I need to replace the numbers based on the below condition.
    if more then 5, replace with many
    if less then 5, replace with a few
    if it is 1, replace with "only one"
    below is my code, I am missing the equating part to replace the numbers could any one of you please help me out fixing this.
    private static String REGEX="(\\d+)";
      private static String INPUT="We have 7 tutorials for Java, 2 tutorials for Javascript and 1 tutorial for Oracle";
      //String pattern= "(.*)(\\d+)(.*)";
      private static String REPLACE = "replace with many";
      public static void main(String[] args) {
      // Create a Pattern object
           Pattern r = Pattern.compile(REGEX);
        // Now create matcher object.
           Matcher m = r.matcher(INPUT);
           //replace the value 7 by the replace string
    //How to equate the (\\d+)  greater than a number  and use it the below code.
                  INPUT = m.replaceAll(REPLACE);
           //Print the final Result;
            System.out.println(INPUT);
    Thanks and Regards,

    Hi,
    Try the following which makes use of  "appendReplacement" instead with the "start" and "end" methods to locate and check the searched "regExp" string before dynamically setting the "replace" string:
    String regExp = "\\d+";
    String input = "We have 7 tutorials for Java, 2 tutorials for Javascript and 1 tutorial for Oracle";
    String replace;
    Pattern p = Pattern.compile(regExp);
    // get a matcher object
    Matcher m = p.matcher(input);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
       Integer x = Integer.valueOf(input.substring(m.start(), m.end()));
       replace = (x >= 5) ? "many" : (x == 1) ? "only one" : "few";
       m.appendReplacement(sb, replace);
    m.appendTail(sb);
    System.out.println(sb.toString());
    HTH.
    Regards,
    Rajen
    P.S: Please mark the post as answered/helpful if it resolves your issue for the benefit of all community members.

  • Java Regex - Find Last Match Using Pattern and Matcher

    I'd like to write some regex which would allow me to grab the last occurance of match based on a specified list of items. So for:
    Pattern languageRegex = Pattern.compile("(len|end)");
    And a string of:
    "00| 0lend|"
    I want it to extract "end". However, I'd grab "len" using the above regex.
    If it was
    "00| 0lenend|"
    I'd grab "end" which is right.
    What regex would allow me to grab "end" rather than "len" from:
    "00| 0lend|"
    Thanks for your help.

    user3940995 wrote:
    I have a list of 3 letter codes that I need to check for in a field. The list is finite but about 100 or so items:
    len, end, ren, onm, enl, etc.
    However, the field I'm checking in has some other data in it which can bleed into the code but the code will always be at the end.
    An example would be "000 0rend"
    From this I'd want to extract "end". If there is a better way to do this than using regex then I'd be happy to use that, but as I have to process millions of items I'm keen to not loop trying to find a match so I was hoping there would be a regex solution.
    Your regex would work for that particular example. I think if I modify it to be
    Pattern.compile("len(?!\\D)|end(?!\\D)|enl(?!\\D)"); (which would then be extended for all the list items)
    Then I seem to pick up the last occurance as I'd like to.
    Thank you for your help!Doesn't sound like you want to use regexp. I would instead build a character graph/tree with my commands in reversed order. I would then search each line backwards and check if it matches something in my tree.

  • 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>

  • How to use javasetters and getters in different classes

    how to use setters and getters in different class so that the setvalue in one class is effect in second class for getting

    If i got your question right,
    make sure your classes are in the same package
    make sure your getters are public/protected
    make sure your code calls the setter before calling the getter
    Kind regards

  • 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

  • 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

  • Using Timer and TimerTask classes in EJB's(J2EE)

    Does J2EE allow us to use Timer and TimerTask classes from java.util package in SessionBean EJB's ( Statless or Statefull )?.
    If J2EE does allow, I am not sure how things work in practical, Lets take simple example where a stateless SessionBean creates a Timer class
    and schedules a task to be executed after 5 hours and returns. Assuming
    GC kicks in many times in 5 hours, I wonder if the Timer object created by survives the GC run's so that it can execute the scheduled tasks.
    My gut feeling says that the Timer Object will not survive.. Just
    want to confirm that.
    I will be interested to know If there are any techiniques that can make
    the usage of Timer and TimeTask classes in EJB's possible as well as reliable with minmum impact on over all performance.

    Have a look at J2EE 1.4. I think they add a timer service for EJBs there...
    Kai

  • 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

  • How to Use JavaScript in Controller Class...

    Hi All,
    Can any one tell me how to use JavaScript in Controller Class.
    Requirement is:
    I have
    Radio Group(RG1),
    Two Radio Buttons(RB1,RB2),
    Two messageTextInput(MTI1,MTI2),
    if i click RB1 i should Prompt to the end user to "Enter value for MTI1" or
    If i click RB2 i should prompt "Enter value for MTI2" while submitting page.
    Please let me know the steps to use JavaScript and the above client validation...
    Regards
    Alem...

    Using javascript is against the standard. I can tell you a workaround instead of you setting the javascript, check if that would be acceptable.
    You can use PPR and set the required property on the messageTextInput on clicking of the radio button. By doing this you will let UIX generate the javascript for you to handle the client side validation. But the validation will happen only on click of the submit button. The visual indicator is good enough to tell that the value has to be entered to the item.

  • How to use image and text in same component

    Hello
    Do you know how to use image and text in same component in java ?
    because i need this in my project ,which is chat application , to
    put the received text and any image if it is need within the text

    thanks levi_h
    JTextPane class extends JEditPane and allows you to embed
    images or other components within the text managed by the component

  • 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

Maybe you are looking for