Deleting the first word in a string

hi! i'm learning regex and with this code i would like to
1) print a string (from "Hi my name is SandraPandra. do not print this")
2) remove the first word and print the new, shorter string
3) remove the first word in the new, shorter string and print the newer and shorter string
4) continue this until it hits a non-character (e.g period, colon, quotation marks etc)
does anyone here know how i should change my code in order to achieve this?
here's my code:
class Testar {
public static void main(String[] args) {
      String partDesc = "Hi my name is SandraPandra. do not print this.";
      do {
           System.out.println(partDesc);
          partDesc = partDesc.replaceFirst("^(\\w+)\\s+","");}
          while (partDesc.equals("\\w") == true);
           if (partDesc.equals("\\w") == false){  //this is where something goes wrong
          System.out.println("found a full stop!");}
} the outcome now is:
Hi my name is SandraPandra. do not print this.
found a full stop!
Thank you in advance!

I answered this question in your previous thread. (Sorry, I didn't realize "I'm going to bed now" was a code for "I won't be reading this thread any more". ^_^ )
I would also like to point out that it's bad form to write conditions like   if ( booleanExpression == true ) It's gratuitously verbose, and it creates the potential for subtle bugs. Suppose the boolean expression is a non-final boolean variable, and you accidentally leave out one of the equals signs:   if ( booleanVariable = true ) An assignment statement evaluates to the value that was assigned, so this "condition" will always be true.

Similar Messages

  • Even more about deleting the first word in a string

    hi, i have this code that removes the first word in a string, returns the shorter string, removes the first word from the shorter string aso... what i would like it to do is to stop when it hits a non-character, but i can't get it to do that. does anyone know why \b won't work?
    import java.io.*;
    class Testar {
    public static void main(String[] args) {
          String partDesc = "Hi my name is SandraPandra.";
          while (partDesc.equals("\b") == false) {  //this is where something goes wrong
              System.out.println(partDesc);
              partDesc = partDesc.replaceFirst("^(\\w+)\\s+","");
    } thanx in advance!

      while (partDesc.equals("\b") == false) That compares partDesc to a string consisting of one backspace character. I suspect you're trying to use the regex word-boundary anchor, but that's a dead end. If you want to stop beheading the string when the regex stops matching, you can write the code exactly that way: class Testar {
      public static void main(String[] args) {
        String partDesc = "Hi my name is SandraPandra.";
        while ( partDesc.matches("^(\\w+)\\s+.*") ) {
          partDesc = partDesc.replaceFirst("^(\\w+)\\s+","");
          System.out.println(partDesc);
    } If performance is a concern, you can use a pre-compiled Pattern object for greater efficiency. Thanks to Matcher's lookingAt() method, you can use the same regex for the test and the replacement: class Testar {
      public static void main(String[] args) {
        String partDesc = "Hi my name is SandraPandra.";
        Pattern p = Pattern p = Pattern.compile("^(\\w+)\\s+");
        Matcher m = p.matcher(partDesc);
        while ( m.lookingAt() ) {
          partDesc = m.replaceFirst("");
          System.out.println(partDesc);
          m.reset(partDesc);
    } The ^ anchor isn't really necessary in this version, since lookingAt() implicitly anchors the match to the beginning of the string, but you might as well leave it in.

  • Delete the first word in a string?

    Hi, i have a code in which i can extract the first three words in a string. after it's found the three first words, i would like it to remove the first one, what could i add?
    this is what the code looks like:
    import java.util.regex.*;
    class Test187D {
         public static void main(String[] args) {
              String word1;
              String word2;
              String word3;
              String partDesc = "Hi my name is SandraPandra";
              Pattern pattern = Pattern.compile("^(\\w+)\\s+(\\w+)\\s+(\\w+)");
              Matcher matcher = pattern.matcher(partDesc);
              //Find the first word of the part desc
              if (matcher.find()) {
                   word1 = matcher.group(1);
                   word2 = matcher.group(2);
                   word3 = matcher.group(3);
                   System.out.println (word1 + " " + word2 + " " + word3);
    } Thank you in advance

    Take the length of the first word, plus one for the length of the space, that's how many characters to remove. Take the substring of the original string from the end of the removed part to the end of the whole string. Look up the String methods length(), and substring().

  • Script to get the first word on each page

    Is there a script that would make a list of the first word of each page (or, preferably, create a text box on each page and place the next page's word in that)? My document's all in one story with one text frame on each page, although there are several other frames (header, page number) applied through master pages.

    You wrote:  I changed the numbers to "8.0425in",  "4.5681in",  "8.1275in", "5.4319in" and it mostly worked - it placed the box at exactly 5 inches (X) and at 8.085 inches (Y) instead of 4.5681 inches. Any idea why?
    No. I cannot reproduce the error you describe. I assume you've checked your numbers very closely in the script--I don't normally indicate measurements as strings.
    you wrote: Something wasn't working with the styling - it kept freezing the program -
    What do you mean by "freezing the program"? Is there a specific error message?
    The paragraph style is named "firstword" and is all lowercase letters?
    firstword paragraph style is NOT in a paragraph style group, right?
    Is the first word on any page too long when formatted with the paragraph style "firstword" to fit in the text frame?

  • Read the first word of each line in a text file

    i need to read the first word of each line of a text file.
    i know of line.split() but not actually sure how i would go about using it
    Any help most appreciated
    Many Thanks
    Ben

    Hi thanks for the reply!
    this is what i tried... and it still doesn't get me the first word of each line!
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.io.*;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import java.util.Calendar;
    import java.util.Scanner;
    import java.util.Vector;
    import java.text.SimpleDateFormat;
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    import java.io.BufferedReader;
    public class testing {
         Vector progs=new Vector();
         Vector rand=new Vector();
         String[] tmp = new String [2];
         String str;
         String str2="ewerwer";
         String str3;
         public void programTest()
                   try
                             BufferedReader in = new BufferedReader(new FileReader("progList.log"));
                             while ((str = in.readLine()) != null)
                                  progs.add(str);
                        catch(IOException e)
                             System.out.println("cannot read file");
         //////THE ISSUES IS HERE....I WANT TO GET THE FIRST WORD FROM EACH LINE OF THE FILE!!!     
              try
                             BufferedReader in2 = new BufferedReader(new FileReader("eventLog.log"));
                             while ((str = in2.readLine()) != null)
                                  tmp = str.split(" ");
                                  System.out.println(tmp[0]);
                        catch(IOException e)
                             System.out.println("cannot read file");
    public static void main(String[] args)
                 testing B = new testing();
                 B.programTest();
               //  B.fileToVector();
                 //B.LoginWindow();
               //B.anomDetect();
    }//end class

  • ID only imports the first word of a 233 page word file (a novel)

    Folks!
    I've tried the old FIle-Place  make a text box and shift+enter..... and I ONLY get the first word of a 60,000 document.  Why?
    I need help ASAP!

    There are a lot of possibilities causing the problem, probably it is caused by some formatting done in Word.
    What text styles are used in Word? Do they have some break options? Repair them in Word.
    Are text boxes/frames used in Word? Remove them in Word.
    Is in Word some kind of break inserted (section, page, column, …)? Remove them in Word.
    But also important:
    When you import the Word file, do you select the import options during import? Do it!
    In InDesign is a character style selected before importing, before choosing the text tool? Don't.
    Because we don't know the source of the Word file it is hard to tell you what it is. A huge problem are Word files which have been converted from PDF or other programs.
    I would try to get rid from any Word imported formatting. Imported styles from Word I would never use in InDesign, I import them often, but I have my own styles predefined in InDesign. After importing I delete step by step the Word formatting. I know, I could map the Word Styles to existing InDesign styles, but in my experience some unexpected things are happening when the Word file comes from someone else than me, because a lot of people have only limitted knowledge when it comes to Word styles and document structure.

  • How can I make iTunes sort on the first word by default, even though that word is "The" or "A"?

    How can I make iTunes sort on the first word by default, even though that word is "The" or "A"?
    I myself think that (for instance) "A tribe called Quest" should be sorted under "A", not "T".
    Now I can edit the sort options manually per track and/or per selection, but I would really like to just kill this "iTunes-knows-how-you-should-sort"-feature in iTunes.
    Anyone any suggestion on how to do that?
    Thanks

    Here is a modified version of one of Doug's Scripts. My modification was to add Sort Name to the list of tags that could be changed. I tried it on a single track and it worked. I recommend backing up your library first. Select the tracks you want to change (or all tracks) and run the script from the Applescript Editor.  If it works as intended, save it so you can apply it to newly imported tracks.  And, yes, I know this isn't the exact answer to your question, you want to change a preference setting in iTunes (if there is such a setting).
    Original script can be forund at http://dougscripts.com/itunes/scripts/ss.php?sp=thistagthattag
    Modified script is below. Start up Applescript Editor, paste it into a new window.  Start up iTunes and select the tracks to modify.  Click Run in the Applescript Editor.  Follow the instructions.
    (* Put This In That
    v2.0 april 22 2008
    - runs as universal binary
    - adds "Show" tag
    - consolidated code
    - saved as script bundle
    v1.7 October 3, 2006
    - adds "Album Artist" as option
    v1.6 October 28, 2004
    - works around iTunes 4.7 selection bug
    v1.5 ('04/1)-- adds "grouping" tag
    Get more free AppleScripts and info on writing your own
    at Doug's AppleScripts for iTunes
    http://dougscripts.com/itunes/
    This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
    Get a copy of the GNU General Public License by writing to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
    or visit http://www.gnu.org/copyleft/gpl.html
    -- CONSTANTS
    property allOptions : {"Song Name", "Artist", "Album", "Album Artist", "Composer", "Genre", "Comments", "Show", "Grouping", "Sort Name"}
    property my_title : "Put This In That"
    global thisTag, thatTag, theNewTags, theOriginalTags, yn
    tell application "iTunes"
              if selection is not {} then -- if tracks are selected...
                        set sel to selection
                        set numTracks to (length of sel)
                        set s to "s"
                        if numTracks is 1 then set s to ""
                        display dialog "The data from one tag REPLACES the data in another tag in all the selected tracks, with option to delete data in first tag." & return & return & (numTracks & " track" & s & " selected.") buttons {"Cancel", "Continue"} default button 2 with title my_title giving up after 30
                        if gave up of result is true then return
                        my choose_this_tag()
                        my choose_that_tag()
                        set yn to (button returned of (display dialog "Delete data in " & thisTag & " afterwards?" buttons {"Yes", "No"} default button 2 with title my_title giving up after 45) is "Yes")
                        set oldfi to fixed indexing
                        set fixed indexing to true
                        repeat with t from 1 to numTracks
                                  tell contents of item t of sel
                                            set theOriginalTags to {get name, get artist, get album, get album artist, get composer, get genre, get comment, get show, get grouping, get sort name}
                                            set theNewTags to theOriginalTags
                                            my do_put()
                                            set {name, artist, album, album artist, composer, genre, comment, show, grouping, sort name} to theNewTags
                                  end tell
                        end repeat
                        set fixed indexing to oldfi
              else
      display dialog "No tracks have been selected." buttons {"Cancel"} default button 1 with icon 0 giving up after 30
              end if -- no selection
    end tell
    to choose_this_tag()
              tell application "iTunes"
                        set n to (choose from list allOptions with prompt ("Select a tag to get data from:") with title my_title)
                        if n is false then error number -128
                        set thisTag to (n as text)
              end tell
    end choose_this_tag
    to choose_that_tag()
              set o to {}
              repeat with t in allOptions
                        if (t as text) is not thisTag then copy t to end of o
              end repeat
              tell application "iTunes"
                        set n to choose from list o with prompt ("Use data from the " & thisTag & " tag to REPLACE data in...") with title my_title
                        if n is false then error number -128
                        set thatTag to n as text
              end tell
    end choose_that_tag
    to do_put()
              try
                        repeat with i from 1 to (length of allOptions)
                                  if thisTag is (item i of allOptions) then
                                            set thisTag_sto to (item i of theOriginalTags)
                                            exit repeat
                                  end if
                        end repeat
                        repeat with i from 1 to (length of allOptions)
                                  if thatTag is (item i of allOptions) then
                                            set (item i of theNewTags) to thisTag_sto
                                            exit repeat
                                  end if
                        end repeat
                        if yn then
                                  repeat with i from 1 to (length of allOptions)
                                            if thisTag is (item i of allOptions) then
                                                      set (item i of theNewTags) to ""
                                                      exit repeat
                                            end if
                                  end repeat
                        end if
              end try
    end do_put

  • Auto-Capitalization: How can I set Pages v5.01 to auto-capitalize the first letter of the first word in a sentence and to automatically change lower case "i" to "I" appropriately. I'm unable to find a menu that offers me these.

    Auto-Capitalization: How can I set Pages v5.01 to auto-capitalize the first letter of the first word in a sentence and to automatically change lower case "i" to "I" appropriately. I'm unable to find a menu that offers me these.

    Gavin Lawrie wrote:
    Once it had been established that the iWork rewrite had resulted in some features being lost and others broken, and once Apple had acknowledged the concerns* and suggested they are working on fixes**, I'm not sure what else there is to achieve.
    You are writing that in the perspective of having read about it here already. Repeated often enough that you encountered it somewhere in the posts.
    Users are flooding in here and don't know any of this. Of course we have to repeat everything endlessly.
    Because I like to give precise, understandable and workable answers to repeated questions, and Apple doesn't allow sticky posts here, I created a separate forum which users can consult to look up real answers, and contribute for themselves if they have something valuable to add:
    http://www.freeforum101.com/iworktipsntrick/
    There is a section purely devoted to Pages 5. Add whatever answers you feel will lighten the problems of Apple's 'upgrades'.
    Peter
    * Where have they acknowledged anything?
    ** They have barely anything listed, compared to the massive list of deleted features, and nothing but an extraordinarily long time frame considering they created the problems here and now. Apple has not said they will do anything at all about fixing the real issues, the biggest of which is that the new iWork apps break virtually all the work of existing users.

  • Replace all up to the first word character

    I have a String with a value of *1. Artist - Title*. What I am trying to do is remove everything up to the first word character so the new String will be Artist - Title. This is all I have been able to come up with:track.replaceAll ("\\d ^\w","").split (" - ");{code} Also, I used {code:java}track.replaceFirst ("\\d","").replaceFirst ("\\W","").replaceFirst ("\\s",""){code}but that isn't practical at all (even though it works).
    I tried to find examples on a few regular expression sites, but maybe I'm not searching with the right keywords. My code won't even compile. Anyone have a hint?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    public class RegexExample3 {
        public static void main(String[] args) {
            String input = "1. Artist - Title";
            String output = input.replaceFirst("^[^A-Za-z]*", "");
            System.out.format("'%s' ==> '%s'%n", input, output);
    }For your requirements, you need to be cleared about "word character", since \w means [A-Za-z0-9]

  • How to delete the last char in a String?

    i want to delete the last char in a String, but i don't want to convert the String to a StringBuffer or an array, who knows how to do?

    Try it in this way
    String MyString = "ABCDEF";
    MyString = MyString.substring(0,MyString.length()-1);

  • Here's how to find the right word in a string

    I needed to find the rightmost word in a string. I didn't find a simple formula in these forums, but I now have one, so I wanted to share it. Hope you find it useful.
    Assuming that the string is in cell A1, the following will return the rightmost word in the string:
    RIGHT(A1,LEN(A1)-FIND("*",SUBSTITUTE(A1," ","*",LEN(A1)-LEN(SUBSTITUTE(A1," ","")))))

    I found the problem. Whatever character was being used in the substitution was parsed out by the forum parser. I replaced it with "œ" (option q on my keyboard).
    =RIGHT(A1,LEN(A1)-FIND("œ",SUBSTITUTE(A1," ","œ",LEN(A1)-LEN(SUBSTITUTE(A1," ","")))))
    Still needs an error check for a single-word "sentence" and to remove the trailing period but it does seem to work. Pretty slick.
    Message was edited by: Badunit
    I see below that the problem was fixed by the OP.
    Message was edited by: Badunit

  • When downloading a file, only the first word of the attached file is included in the 'file name' field, not the entire file name, as it used to.

    Regardless of filetype, only the first word of the file is filled into the "Enter name of file to save to..." dialog box. I'm set up to 'save file' in the FF Options > Applications tab for the basic MS and Adobe files. To successfully use/find the downloaded file, I type in the remainder of the file name. Have I overlooked an additional setting? Running FF 18.0 on a Win7 PC.

    Start Firefox in <u>[[Safe Mode|Safe Mode]]</u> to check if one of the extensions (Firefox/Tools > Add-ons > Extensions) or if hardware acceleration is causing the problem (switch to the DEFAULT theme: Firefox/Tools > Add-ons > Appearance).
    *Do NOT click the Reset button on the Safe mode start window or otherwise make changes.
    *https://support.mozilla.org/kb/Safe+Mode
    A possible cause is that the server sends a wrong response header.
    The server may not comply to RFC 5987 and sends a wrong Content-Disposition:attachment; filename header.
    * https://developer.mozilla.org/en/Firefox_8_for_developers#Network

  • When I type the first word's letters are always mixed up

    using an Apple  extended USB keyboard that came with my mac pro (2x 3ghz Dual Core Xeon processor, 18gb 667MHz RAM)
    It's like the Mac cant react fast enough to catch the first one or two letters and it just inserts them into the middle of the first word.
    like "Hello" would be "ellHo" and "OK" is "KO"
    the rest of the sentence is fine. or the rest of the paragraph, it seems to inly happen when I first select a text field or when I have been idle for mor ethan 30 seconds.  this happens in all apps. Mail, Firefox, Textedit etc.
    i have not yet unplugged the rest of my USB peripherals but that is my next step.
    Ihave a ADF scanner, multifuncion printer, logitech wireless mouse, usb plantronics headset, iMo 7" USB monitor. running os 10.7.2
    just upgraded and everything was fine in 10.6.x.
    anyone else experience this?
    thanks
    Steve

    I have similar problems with an Apple Wireless Keyboard (Bluetooth) and a MacBook Pro since installing Lion  I am running 10.7.2 also.   See https://discussions.apple.com/message/16701228#16701228 for more detail.  I think it's a bug in Lion.

  • The system doesn't recognize or capitalize the word (I) or the first word of every sentence. Another really annoying thing about the integrated mail on your Mac computers is the fact that the system learns the word as you type it more and more instead of

    The system doesn’t recognize or capitalize the word (I) or the first word of every sentence. Another really annoying thing about the integrated mail on your Mac computers is the fact that the system learns the word as you type it more and more instead of highlighting it as incorrectly is this is a word that’s being misspelled. Can Apple fix this bug to make it user friendly as if you were using Office or a Word Document?

    You hit the target CT.
    It’s only fair that if Apple is going to integrate Mail into Mac PCs, it would be nice if the system does it for you like Office or perhaps Outlook. I just don’t to use Outlook although I have it installed and ready to use, but instead use Mail which comes with Mac OS already.
    I hope to make some sense here.

  • Last night I downloaded the latest Word update. Today the first Word document crashed and I lost 45 minutes of work in spite of having saved the document numerous times. Why is Word crashing the day after a safety update? I have Office 2008 for Mac

    Last night I downloaded the latest Word update. Today the first Word document crashed and I lost 45 minutes of work in spite of having saved the document numerous times. Why is Word crashing the day after a safety update? I have Office 2008 for Mac

    One way to test is to Safe Boot from the HD, (holding Shift key down at bootup), run Disk Utility in Applications>Utilities, then highlight your drive, click on Repair Permissions, Test for problem in Safe Mode...
    PS. Safe boot may stay on the gray radian for a long time, let it go, it's trying to repair the Hard Drive
    Reboot, test again.
    If it only does it in Regular Boot, then it could be some hardware problem like Video card, (Quartz is turned off in Safe Mode), or Airport, or 3rd party add-on, Check System Preferences>Accounts>Login Items window to see if it or something relevant is listed.
    Check the System Preferences>Other Row, for 3rd party Pref Panes.
    Also look in these if they exist, some are invisible...
    /private/var/run/StartupItems
    /Library/StartupItems
    /System/Library/StartupItems
    /System/Library/LaunchDaemons
    /Library/LaunchDaemons
    Open Console in Applications>Utilities, check the system log for the date/time of the last problem  & next startup for clues.

Maybe you are looking for

  • Iphone 5 no longer recognizes apple lightening cord to charge

    So I have been on a quest the last few days to try and find out why out of the 4 iPhone users in our house, only 2 of us, owning the iPhone 5, have issues with cords and charging our phones.We have owned every generation of iPhones and own everything

  • Apps won't update! iPod touch 2nd gen!

    I have a almost brand new ipod touch and normally when i have wifi little red numbers will pop up about undates for pre-existing apps, & ill just click "update all" and it works. but now, I press "update all" and it starts to work and then a little m

  • AS2 equivalent of Document class?

    Is there a way in AS2 to approxmiate the functionality of assigning a document class to a FLA/published swf? I would like to publish a swf that is an instance of a Topic class (extends movieclip). For various reasons I can't use AS3, but I would real

  • Error while creating Asset Mastere Record

    Hi Gurus, When I am creating the AMR by using the transaction code AS01, below metioned error is poping up; Serial number already exists for asset number INTERN-00001 Message no. ZFI_FA_VAL000 Could you please let me know, what is the INTERN, and I a

  • Permanent Regional Formatting, Save for all users, Remove Document Security

    Dear Experts, I have read the Documentation of Permanent Regional Formatting, Save for all users, Remove Document Security in Document Properties. Can anyone explain me in simple way all the above three. (More on Permanent Regional Formatting with ex