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.

Similar Messages

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

  • 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().

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

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

  • My Ipod was originally set up as a sub-account of a firends.  After that, I got an Iphone and set up my own Apple account.  I just got a new Ipod, and now can't sync my old Itunes to it. Can anyone help me? I'm even OK with deleting the old Itunes account

    My Ipod was originally set up as a sub-account of a firends.  After that, I got an Iphone and set up my own Apple account.  I just got a new Ipod, and now can't sync my old Itunes to it. Can anyone help me? I'm even OK with deleting the old Itunes account, and staring over.  I just really want to get the new Ipod under my own account, and be able to use it...

    There is no such thing as a "sub-account."  Also, you probably mean iTunes library, when you say "account."  Your "account" in iTunes is your Apple ID, which is what you use to sign in to the iTunes Store to make purchases.  iPods are associated with an iTunes library, not with an Apple ID (iTunes Store account).  You'll need to clarify...
    So, this is what I think you are saying.  You previously shared an iTunes library on a computer with your friend.  Your old iPod was synced to that iTunes library. 
    You got an iPhone, and at that time, you set up your own iTunes library.  Is that on a different computer?  How does the iPhone affect your question about the iPod?
    You got a new iPod.  What is your "old iTunes"?  Is that the iTunes library you shared with your friend?

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

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

  • Is there a way to capitalize just the first word on a sentence on Pages v5.2?

    I'm sort of new to iwork, but i've been working with word for a long time and i know it very well.
    In word there is a tool in which you select a paragraph and you can capitalize the first word of each sentence.
    Is there a way i can do the same with pages v5.2? Pages would only let me capitalize each word of the selected paragraph.
    Thanks

    The previous major version of Pages (Pages '09 version 4.3) could automatically capitalize the first word of each sentence as you typed. That capability and a number of others was lost with the release of Pages v 5. You may still have the older version available in your Applications folder. You may also want to switch to Word or Open Office (free), both of which will likely be more familiar if you have worked with Word before.

  • Apple Mail - how to get the first word in a sentence to auto-capitalize

    How to get the first word in a sentence to auto-capitalize
    Anwar

    something to look forward to then, because we get used not to use our shift button any more, since iPhone and iPad do it for us. entourage and other ms stuff do it. pages does it too now (put it on in the auto-correct in preferences). bizarre however some loose the capitalization when you copy the text. pages to stickies or mail does not. that's good !

  • Php delete the first record in an xml doc

    So I have a shoutbox, and I only want it to store about 300
    results, and the only way I can think of doing that is to fill it
    with three hundred results, and then delete the first one every
    time a new one is added, but I can't find a way of doing this in
    php.
    Help?

    Hello,
    You can use function module CRM_MESSAGES_DELETE.
    First of all you'll need to pass an internal table to IT_R_MSGID or IT_R_MSGIDNO with a structure like for example:
    ls_msgidno-msgid    = 'CRM_COMPLAINT'.
    ls_msgidno-msgno   = '002'.
    ls_msgidno-low        = lv_some_input
    Then you can call the FM as follows:
    CALL FUNCTION 'CRM_MESSAGES_DELETE'
         EXPORTING
           it_r_msgidno  = [your internal table]
           iv_ref_object   = [your object, for example an order guid]
           iv_ref_kind      = gc_object_kind-orderadm_h => for a bus. trans. this will be 'A',
                                                                                 for an order item, this will be 'B', etc.
         EXCEPTIONS
           OTHERS        = 0.
    Kind regards,
    Tom.

  • With one of the last updating in Adobe Reader,in the "recently read" section,it's no more possible delete the last pdfs read

    With one of the last updating in Adobe Reader,in the "recently read" section,it's no more possible delete the last pdfs read. Can that be changed? Before in fact there was a specified button for that!

    Hi,
    The 'Clear Recents' button which was provided in previous releases only *cleared* the Recent list and did not delete the files. The files stayed in your document hierarchy. This button has been removed in the latest release. For deleting the files, you can go to the Documents/Acrobat.com tab and delete the files individually. However, please note that the files will be permanently deleted from your device. Please let us know if this is not a viable option for you. We would like to hear more about your use case for which you would require to just remove the entry from Recents and not delete the file. You could share the feedbacks here.
    Thanks,
    Shefali

Maybe you are looking for

  • Trigger problem -- can't insert the same data into audit table

    Sir/Madam, I'm trying to use insert trigger with a 'long raw' datatype data for my audit purpose. Each time, the data of original table can be inserted correctly. While the trigger for audit table in which it contains almost the same data as original

  • Cannot add VM to Cluster

    We have have Hyper-V 2012 Cluster with 2 Nodes that runs about 10 VMs, mostly Server 2008 R2 with a few 2012. Cluster storage is and iSCSI SAN with DSS7 from Open-e. I have a VM that I cannot add to the Cluster.  Its Server 2012 that runs Exchange 20

  • Firefox does not start on second desktop

    I am using the free Sysinternals product called [http://technet.microsoft.com/en-us/sysinternals/cc817881.aspx Desktops ] (desktops.exe) to allow for more than one desktop in Window 7. Not too long ago, I used to be able to start a Firefox instance o

  • Best practices: Invoking external webservices with user credentials

    Hello Experts, I just need to store and maintain a couple of user credentials when invoking external web servcies. I was thinking of storing them in system-jazn-data.xml as I thought it was easier to change the password due to policy requirements thr

  • What's the best phone app to use on iPad for uk users to make calls with

    I know there's a few apps out there to use and make phone calls with, but which is the best one for uk users/callers. I would prefer not to use Skype but if that's the best on the market, that's what I will use. As you can probably guess I'm new to t