Results 1 to 17 of 17
  1. #1
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default LineNumber.java - beta testers needed

    PLEASE SCROLL TO THE BOTTOM FOR THE LATEST VERSION.
    THIS PROGRAM HAS BEEN REVISED TO USE THE SYSTEM CLIPBOARD INSTEAD OF THE CONSOLE FOR I/O.


    --ORIGINAL POST--
    It ain't much, but its a start. I have no clue how to add gpl licenses and javadoc tags, guess its time to start looking into that...

    Java Code:
    LineNumber V0.1 beta - Strips/Appends Line Numbers.
    
    USAGE: java LineNumber -s filename n > newfile.java
    USAGE: java LineNumber -a filename   > newfile.txt
    
      -s:  Strip n Characters
      -a:  Appends line number
      -h:  Help Menu
       n:  Any integer number
    Java Code:
    [PHP]
      1. /** LineNumber V0.1 beta - Strips/Appends Line Numbers.
      2.     Copyright (C) 2009  AngryBoy @ http://www.java-forums.org
      3. 
      4.     This program is free software: you can redistribute it and/or modify
      5.     it under the terms of the GNU General Public License as published by
      6.     the Free Software Foundation, either version 3 of the License, or
      7.     (at your option) any later version.
      8. 
      9.     This program is distributed in the hope that it will be useful,
     10.     but WITHOUT ANY WARRANTY; without even the implied warranty of
     11.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     12.     GNU General Public License for more details.
     13. 
     14.     You should have received a copy of the GNU General Public License
     15.     along with this program.  If not, see <http://www.gnu.org/licenses/>.
     16. */
     17. 
     18. import java.util.Scanner;
     19. import java.io.*;
     20. 
     21. public class LineNumber{
     22.    private static int error = 0;
     23.    
     24.    public static void main(String[] args){
     25.       String param = null;
     26.       String fileName = null;
     27.       try{
     28.          param = args[0];
     29.          fileName = args[1];
     30.       }
     31.       catch(ArrayIndexOutOfBoundsException ex){
     32.          printHelp();
     33.       }
     34.       if(param.equals("-s")){      
     35.          int n = 0;
     36.          try{
     37.             n = Integer.parseInt(args[2]);
     38.          }
     39.          catch(ArrayIndexOutOfBoundsException ex){
     40.             printHelp();
     41.          }
     42.          catch(NumberFormatException ex){
     43.             printHelp();
     44.          }
     45.          
     46.          StringBuilder sb = stripChar(fileName,n);
     47.          System.out.println(sb);
     48.          System.out.println("\n\nTotal StringIndexOutOfBoundsException: "+error);
     49.       }
     50.       else if(param.equals("-a")){
     51.          StringBuilder sb = appendChar(fileName);
     52.          System.out.println(sb);
     53.       }
     54.       /*
     55.       else if(param.equals("-h")){
     56.          printHelp();
     57.       }
     58.       */
     59.       else printHelp();
     60.    } // end main method
     61.    /** This method prints the help menu.
     62.    */
     63.    private static void printHelp(){
     64.       StringBuilder help = new StringBuilder(50);
     65.       help.append("LineNumber V0.1 beta - Strips/Appends Line Numbers.\n");
     66.       help.append("Copyright (C) 2009  AngryBoy @ http://www.java-forums.org\n\n");
     67.       help.append("USAGE: java LineNumber -s filename n > newfile.java\n");
     68.       help.append("USAGE: java LineNumber -a filename   > newfile.txt\n\n");
     69.       help.append("  -s:  Strip n Characters\n");
     70.       help.append("  -a:  Appends line number\n");
     71.       help.append("  -h:  Help Menu\n\n");
     72.       help.append("   n:  Any integer number\n");
     73. 
     74.       System.out.println(help);
     75.       System.exit(2);
     76.    }
     77.    /** Strip n number of characters from beginning of each line.
     78.       // param stuff here
     79.    */
     80.    public static StringBuilder stripChar(String fileName, int nChar)
     81.    {
     82.       StringBuilder sb = new StringBuilder();
     83.       Scanner in = null;
     84.       try{
     85.          in = new Scanner(new File(fileName));
     86.       }
     87.       catch(FileNotFoundException ex){
     88.          System.out.println("ERROR: File was NOT Found.");
     89.          System.exit(1);
     90.       }
     91.       while(in.hasNextLine()){
     92.          // read then strip n characters.
     93.          try{
     94.             sb.append(in.nextLine().substring(nChar));
     95.          }
     96.          catch(StringIndexOutOfBoundsException ex){
     97.             error++;
     98.          }
     99.          // add a new line.
    100.          sb.append("\n");
    101.       } // end while loop
    102.       in.close();
    103.       return sb;
    104.    } // end stripChar method.
    105. 
    106.    /** Adds a line number to each line.
    107.       // param stuff here
    108.    */
    109.    public static StringBuilder appendChar(String fileName){
    110.       StringBuilder sb = new StringBuilder();
    111.       Scanner in = null;
    112.       try{
    113.          in = new Scanner(new File(fileName));
    114.       }
    115.       catch(FileNotFoundException ex){
    116.          System.out.println("ERROR: File was NOT Found.");
    117.          System.exit(1);
    118.       }
    119.       int lineNum = 1;
    120.       while(in.hasNextLine()){
    121.          // align line number digits.
    122.          if(lineNum < 10) sb.append("  "+lineNum+". ");
    123.          else if(lineNum < 100) sb.append(" "+lineNum+". ");
    124.          else sb.append(lineNum+". ");
    125.          
    126.          // read then strip n characters.
    127.          sb.append(in.nextLine());
    128.          // add a new line.
    129.          sb.append("\n");
    130.          lineNum++;
    131.       } // end while loop
    132.       in.close();
    133.       return sb;
    134.    } // end appendChar Method.
    135. } // end LineNumber class
    [/PHP]
    Attached File is the non-line numbered version. Just rename to .java and compile.
    Attached Files Attached Files
    Last edited by angryboy; 01-30-2009 at 05:59 AM.
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  2. #2
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Cool what do you need.

    Okay, for your license - say what you want.

    The people who make licenses necessary won't read your license. The one's who will read it may waste time contemplating DRM - which is a great idea but does not seem to work. Write code faster than people can worry about your license. I can host your code for a few days if there are no problem cases getting involved, Problem with GNU is that it was written by a bunch of folks who go to seven corners trying to get rid of those people, and in doing so make it that you have to comply their world-view. Use Creative Commons instead.

    By far, Don Lancaster's "The Case Against Patents" is for sure the most informative work you could read or devote time to right now, concept distorting - paradigm tinkering work beyond the level of Ph.D.

    In general, a legal license cannot be copyrighted - if you see something you like - you can subvert it to your own needs with just the extraction of brand names and such as that.

    Javadoc is as simple as write what you would say to someone of your own caliber and skills, as though they sat in a chair within hearing range. Add some super-simple html if that does not slow you down...

    Tell me what your program is supposed to do, I will test it and enhance it and....

    uh..

    you won't get angry at me, will you?
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  3. #3
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    "you won't get angry at me, will you?"
    Why would I, don't really care about licenses for these small scripts. Just thought that its better than having nothing, that is, being unprotected.

    The program adds or strips away line numbers from whatever file you give it. I thought it was clear from the code line, but I guess not.
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Have you considered making it non-static, with the idea of making this the "Model" of a yet to be created Swing "View" class?

  5. #5
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    non-static or api... maybe. Swing, no. But maybe a gui front end.
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  6. #6
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default

    Java Code:
    if(lineNum < 10) sb.append("  "+lineNum+". "); 
    else if(lineNum < 100) sb.append(" "+lineNum+". "); 
    else sb.append(lineNum+". ");
    can be replaced by
    Java Code:
    sb.append(String.format("%3d. ", lineNum);
    Easier to read, and to increase the field width, you only have to make one change.

    db

  7. #7
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    Thanks DB. Line 122-124 has been replaced by:
    sb.append(String.format("%3d. ", lineNum));
    // credited to Darryl.Burke @ http://www.java-forums.org

    Also, line 48 is changed from System.out to System.err...
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  8. #8
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Lightbulb minor comments

    Daryl made the only improvement I would have found, my remarks were directed at some obscure issues that probably are ahead of what appears to be at hand. I did some work just so I put some work into this:
    Java Code:
       private static String  lineEnding = System.getProperty("line.separator");//
       public static void main(String[] args){
          String param = null;
          String fileName = null;
          try
          {
              // Yes, I know != 
              if((args.length > 2) || (args.length < 2))
              {
                  printHelp();
                  return;
              }
              else
              {
                 // get parameters
                 param = args[0];
                 fileName = args[1];
                 // .... rest of program goes here ....
          }
          catch(ArrayIndexOutOfBoundsException ex)
          {
              System.out.println("An unkown error happend: "+ex.getMessage());
              System.out.println(lineEnding + lineEnding + "don't get angy");// JOKE !!! ...
              return;
          }
    My angry comment was jus so that I am paying attention - I would give deeper review to Fubarable's observation, this should be a data model, or in the data model, a front-end to data that gets passed to the data model.

    My fundamental question remains: What is this for? Which, obviously, is addressed in your comments and posting - it is a first project, or that sort of thing.

    In other words, target some problem domain - make it do something useful. If there is some need you have encountered to remove the first n characters of every line ~ so state. This would be where Fubarable would be going with the data model observation. Licenses are a waste of time, if you want to know why - read Snake Oil by Matt Curtin
    And how secure is secure enough? Does the data need to be unreadable by ``spies'' for five minutes, one year, or 100 years? Is the spy someone's kid sister, a corporation, or a government?
    he has a copyright notice - what for? DRM is a failed concept, protect yourself: Professional Counsel rates start at $340 an hour, can go as high as $3,400 an hour.

    You posted some code in a discussion in a techical forum, that's not exactly where the risk is.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  9. #9
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    Oh! I forgot to check for args.length. Thanks NJ, thats the kind of debugging I'm looking for. And you're right, I was trying to cram everything into a single file for easy uploading.

    What is this used for: For stripping away line numbers to code examples found in ebooks. And also add line numbers, if needed.

    This is the new version, and it includes a sample main. It is rewritten for reuse.

    PHP Code:
    /**
    * @(#)LineNumber.java
    *
    * LineNumber application, Public Domain
    * This class can add or strip away line numbers.
    *
    * @author AngryBoy @ http://www.java-forums.org
    * @version 1.01 2009/1/18
    */
    
    import java.util.Scanner;
    
    
    public class LineNumber {
       private String data;
    
       public static void main(String[] args) {
          String s = "abczz\n123\n\nxyzgee\n987brg\n\n\n";
          
          System.out.println("--Original String--");
          System.out.println(s);
          
          LineNumber t = new LineNumber();
          
          // Test appending LNs.
          t.setData(s);
          t.appendLineNumbers();
          s = t.getData();
          System.out.println("--LN Appended--");
          System.out.println(s);
          
          // Test stripping LNs.
          t.setData(s);
          int error = t.stripLineNumbers(1);
          
          s = t.getData();
          System.out.println("--LN Stripped--");
          System.out.println(s);
          System.err.println("Stripping Errors: "+error);
          
       } // end main
       
       // CONSTRUCTORS
       public LineNumber(){
          this.data = " ";
       } //end d.c.
       
       public LineNumber(String data){
          setData(data);
       } // end ln
       
       
       // GET-SET METHODS
       public String getData(){
          return data;
       } // end getData
       
       public void setData(String data){
          this.data = data;
       } // end setData
       
    
       /** Strips line numbers
       *  from data for n characters.
       */
       public int stripLineNumbers(int nChar)
       {
          Scanner in = new Scanner(data);
          // initialize & ensure capacity of stringbuilder.
          StringBuilder sb = new StringBuilder(data.length());
    
          int exCount = 0;
          while(in.hasNextLine()){
             // read then strip n characters.
             try{
                sb.append(in.nextLine().substring(nChar)+"\n");
             }catch(StringIndexOutOfBoundsException ex){
                exCount++;
                sb.append("\n");
             } // end try-catch
          } // end while loop
          
          in.close();
          data = sb.toString();
          
          // returns a count of StringIndexOutOfBoundsException(s).
          return exCount;
          
       } // end stripLineNumbers method.   
    
    
       /** Appends a line number.
       */
       public void appendLineNumbers(){
          Scanner in = new Scanner(data);
          // initialize & ensure capacity of stringbuilder.
          StringBuilder sb = new StringBuilder(data.length()*2);
          
          for(int lineNum = 1; in.hasNextLine(); lineNum++){
             // credited to Darryl.Burke @ http://www.java-forums.org
             sb.append(String.format("%3d. ", lineNum));
             sb.append(in.nextLine()+"\n");
          } // end while loop
          
          in.close();
          data = sb.toString();
          
       } // end appendLineNumbers Method.
       
    } // end LineNumber class.
    Logic bug found and removed.
    Last edited by angryboy; 01-19-2009 at 12:24 AM.
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  10. #10
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    8

    Default

    Just put a note saying it is "Public Domain". That means anyone can use for anything.

  11. #11
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    I edited it, like the above?
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  12. #12
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Lightbulb Major improvements.

    License much better, PD pretty much resolves the issue. Still using backslash n - try
    Java Code:
    static final String lineEnding =
              new String(System.getProperty("line.separator"));
    and ( probably ) use re's to achive stated purpose...

    rather involved so shortend version is that some of the string find and/or replace methods will accept re directly in the method call. To find ( and eliminate ) one or more numerals at exactly starting at the very front of the line, you can use ^\d+ which to be coded in a string has to be escaped escape ( ? ) which would be "^\\d+" or maybe "^\\d?" or "^\\d*" I forget which one it is and use + for everything until I have a chance to think through the regex.

    What that does is find the numerals at the beginning of the line but it's inverse logic - what you want is all that is not numerals right at the front of the line. Be prepared to get a copy of Mastering Regular Expressions by Jeffery E.F. Friedl and a multi-month work to get going on them. Once you figure out whether it's + or ? or * the next step is how to get everything else. The first approach I know of is "^\\d+(.*)" which reads as beginning of line followed by one or more digits, then captured separately zero or more of anything else. That is called a capturing group, you can get the results of the capturing group separate from the numerics ..... read docs for java.util.regex.Pattern and java.util.regex.Matcher ( with the book ! )

    What is NP++ (?)

    I bet Steve could write the regex for what you want and discuss some of the issues on crafting the regex correctly, deceptive and tricky but this is a common task so likely there are plenty of places to start.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  13. #13
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    8

    Default

    NP++ is a free, text-based word processor for programmers.

    There are lots of sites with regular expression tutorials and references. Here's one.

    The "^" character serves two purposes. As the first character in a character class "[^...]" it means "not any of the following". Outside of the [], it means start of line. So,

    ^\d+

    means start of line, followed by one or more digits.

    When a regular expression is placed inside a String literal, all the backslashes have to be escaped with a backslash: "\\" == \

    An easy way to replace the leading digits in a String is to use the replace(String regex, String replacement) method.

    String newString = "1234 Some text. 5678".replace("^\\d+", "");

    results in newString containing " Some text. 5678".

  14. #14
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default new stripLineNumber()

    Thanks for the suggestions. Please double check the regex for me. One reason I did not use regex from the beginning is that NotePad++ includes a "delete line number" plugin which is unreliable because it uses regex. But as it turns out, java's regex is pretty good.

    *This has not been tested with other code examples other than those found in core java.

    Here is the new method:
    Java Code:
       /** Strips line numbers from data.
        */
       public void stripLineNumbers(){
          Scanner in = new Scanner(data);
          // initialize & ensure capacity of stringbuilder.
          StringBuilder sb = new StringBuilder(data.length());
    
          int exCount = 0;
          while(in.hasNextLine()){ // read then strip n characters.
                // regex suggested by Nicholas Jordan @ http://www.java-forums.org
                // match any -space- -digit- -specialChar- -space-
                [B]String s = in.nextLine().replaceFirst("\\s*\\d+[\\D|\\W]?\\s?","");[/B]
                sb.append(s + "\n");
          } // end while loop
          
          in.close();
          data = sb.toString();
       } // end stripLineNumbers method.
    --------------------
    This program takes text from the system clipboard, and appends a line number in front of each line, then copies the results back to the clipboard. It also does the reverse, see usage guide for more info.

    Java Code:
    USAGE:
      C:\LineNumber.jar       // Add line numbers
      C:\LineNumber.jar X    // Where X is anything. Strips line numbers.
      C:\LineNumber.jar -e   // Same as X, but shows errors.
    Here's the complete working code. It makes use of the system clipboard. It appendsLN by default, but if args.length != 0, then it stripsLNs.
    Src is included. File needs to be renamed to .jar from .txt.
    Attached Files Attached Files
    Last edited by angryboy; 01-27-2009 at 08:26 AM. Reason: file attachment
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  15. #15
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Thumbs up All Caveats apply

    Overview (Java 2 Platform SE 5.0)
    java.util.regex (Java 2 Platform SE 5.0)
    Pattern (Java 2 Platform SE 5.0)
    Matcher (Java 2 Platform SE 5.0)


    String s = in.nextLine().replaceFirst("\\s*\\d+[\\D|\\W]?\\s?","");

    \s* - zero or more whitespace - iow first number may not be right at beginning of line.
    \d+ - one or more digits
    [\D|- one non-digit
    [\W]? - once or not at all : non-word character
    \s? - once or not at all of any of newline, tab, formfeed,.....uhm, timeout...

    remarkable progress for first attempt plus the note about unreliable is probably the single most important issue we can work here.

    Let's step down from Boogie Level One and work on specific details of the proposed regex.

    First thing I saw was "," which probably should be \",\" or you get a compile error of some kind. So first thing is do:
    Java Code:
    try
    {
        String s = in.nextLine().replaceFirst("\\s*\\d+[\\D|\\W]?\\s?","");
        ;
    }
    // http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/PatternSyntaxException.html
    catch(PatternSyntaxException pse)
    {
        ;// ????...what to do.
    }
    there is no easy way to propagate the error, if any, out of the funcntion. Working this small section of code, I can figure out that the "," is actually part of the function call and not a regex error. Okay,...but what if you acclimatize to this code pattern and later write a regex that throws?

    Next thing I see is one or zero of tab, newline, etc which brings to mind one of my first regexes where I tried to code \\b in a string to find or not find backspace character from keyboard. A master observed that I was not coding what I thought I was coding. Then there is zero or one of that or non-word character.

    Okay, do you really know that someone will not pirate the code? In a real shop, someone takes you code with no idea how to use it and splats it somewhere, then you get hickyed - code defensively, like someone is trying to take your pizza away from you. ( which they will )

    How do you know it is one or none of D or W ?

    Then, try to use ^ and $ whenever it makes sense, I skip $ in Java because there is an issue ( bug report ) that I have not had the time to dig into but regex expression for beginning of line and end of line aid the tool greatly in efficiency issues.

    Now, my 2-cents: Rather than zero or more of whitespace, which can runaway sort of, what you are actually looking for is NOT digits, probably zero or more at the beginning of line, followed by zero or more digits, capturing whatever else follows - so it's:

    Java Code:
    ^\s*\\d*(.*)
    then use capturing groups to go after the comma as you have it. ( let Steve critiqe this as he obviously has more time at it )

    In summary, it's your comment about the abandonment of re's completely due to failure in a shipped product.

    That is where I am the Master, I do that on massive projects. Set down everything here, focus on Regexes - attain resources.

    The is core cs, leads to virtualy the entire challenge domain. All Caveats apply, except as noted in the Caveat Correction Manual, General Notes as amended. ( bazillionth revision - just trying to post I already made two changes, going back to what you had at the beginning )
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  16. #16
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    Next thing I see is one or zero of tab, newline, etc which brings to mind one of my first regexes where I tried to code \\b in a string to find or not find backspace character from keyboard. A master observed that I was not coding what I thought I was coding. Then there is zero or one of that or non-word character.

    Okay, do you really know that someone will not pirate the code?...
    *CONFUSED* Sorry NJ, i'm having a hard time following you... gona need some clarification...

    Lets start with this.
    Java Code:
    // String regexStr = "^\\s*(\\d+[\\D|\\W]?)\\s?";
    
    String regexStr = "^\\s*\\d*(.*)"; // work in progress...
    
    String s = in.nextLine().replaceFirst(regexStr,"");
    and thanks for the hint on "PatternSyntaxException", didn't know about that.
    (and prob pattern-matchers later on).
    Last edited by angryboy; 01-22-2009 at 07:53 PM.
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  17. #17
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Thumbs up clarification...

    *CONFUSED* Sorry NJ, i'm having a hard time following you... gona need some clarification...
    i do that a lot, just skipped ahead to give you some room to work as you seem to be able to make progress when someone does that for you. What I was doing there is reading the regex ( or trying to ) as that will shortly come to your skill set and is needful trying to read one of these things.

    Java Code:
    // String regexStr = "^\\s*(\\d+[\\D|\\W]?)\\s?";
    
    String regexStr = "^\\s*\\d*(.*)"; // work in progress...
    
    String s = in.nextLine().replaceFirst(regexStr,"");
    Good, we get to the point - what this code does is interesting for the student who wishes to do actual computer science.

    What you are trying to do is .... timeout - grasp this .... find characters that are NOT ( hollering for clairty, not flashpoint ) not .. digits ... there might be a space or something, thus to achieve that you code code to find that.

    Okay, so good, so far. Or is it? Actually, what you want is not ... some sort of whatchamacallit that fits some ... at least we hope it fits, some sort of definite code construct that we can place here.

    Okay, I had to do just exactly this a few days ago. I actually needed a program to run so that I could use it. I resorted to designing a pattern that was not likely to be in the datastream. Then I coded
    Java Code:
    Pattern.compile("RECEIVE_DATE([^#]+)");//
    and placed the data between "RECEIVE_DATE" and "#" in the actual file.

    Regexs are challenging in that a tradional problem of the the dataset either has to have a control structure outside of the dataset or special characters in the dataset. That leads to some challenges that waste time in all-nighters staring at the screen in contemplation.

    Your code is being written for a definite task that can be given parametric bounds. We know that in all realistic cases the numbers will be at the beginning of the line, thus we are not presented with what to do to with numerics that are not at the beginning of the line. Okay, we have a double inversion running here.

    Regex has a tool that will fit the job. It is called lookahead and lookbehind.

    Java Code:
    // Special constructs (non-capturing)
    // // (?:X)   X, as a non-capturing group
    // (?idmsux-idmsux)    Nothing, but turns match flags on - off
    // (?idmsux-idmsux:X)      X, as a non-capturing group with the given flags on - off
    // (?=X)   X, via zero-width positive lookahead
    // (?!X)   X, via zero-width negative lookahead
    // (?<=X)  X, via zero-width positive lookbehind
    // (?<!X)  X, via zero-width negative lookbehind
    // (?>X)   X, as an independent, non-capturing group
    So what we can actually do here is
    Java Code:
    (?<=^(\\s|\\d))(.*)
    Which to avoid posting reply that is too bulky, let me let you struggle with this awhile: Try to read it, read the docs, give it ten hours worth of work or greater just trying to read what I just wrote and do some test harness work on just this one line in one module pulled to a short progam ....

    Try not to get frustrated or disappointed, then place \1 ( that would be "\\1" in a Java Regex.compile() ) in the String.replace as you had it, behind the comma.

    I don't know if is is \1 or \2 or if we should do String.replace((?<=^(\s|\d)).*,\0); but then I would be doing your work for you.

    As the Internet grows, so does the need for scalable Internet services. Popular web servers are asked to deliver content to hundreds of millions of users connected at ever-increasing bandwidths. The model of centralized, monolithic servers that are responsible for all aspects of every client's request seems to be reaching the end of its useful life.

    Someting like a well crafted regex that has undetected failure modes could bring a world already on it's knees to the actual the end of its useful life.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

Similar Threads

  1. XMLUnit 1.1 Beta 2 (For Java)
    By levent in forum Java Software
    Replies: 1
    Last Post: 01-07-2012, 09:06 AM
  2. My first game - Need beta testers and comments
    By onemind in forum New To Java
    Replies: 1
    Last Post: 11-12-2008, 06:45 PM
  3. Java checkstyle Tool 5.0 beta 1
    By Java Tip in forum Java Software
    Replies: 0
    Last Post: 07-19-2008, 05:20 PM
  4. Java experts needed- 30 minute online Java projects
    By michelle in forum Jobs Offered
    Replies: 0
    Last Post: 03-06-2008, 12:47 AM
  5. Java help needed
    By jeneal in forum New To Java
    Replies: 0
    Last Post: 11-21-2007, 04:04 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
  •