Match first word in a String

I'm writing a program to reorganize some music. And I have a special case where bands that begin with 'The' need to be organized differently. So I'm writing a method to rename the music directories, but I am having trouble figuring out how to determine if the artist name begins with 'The'. Can someone point me in the right direction as to which java tool would help me in determining this case. The artist names are being passed in as Strings. TIA.
Edited by: prem1ers on Dec 21, 2009 7:27 PM

prem1ers wrote:
Ok, thank you. I am not so comfortable with regex, so I will look for the easier way. Thanks again.Hint: if you are looking for "begins with", you're on the right track but not using quite the correct words to find the most suitable String method.

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.

  • Match Certain word in a String

    Hi all,
    I'm actually doing a project regrading e-learning. And i'm suppose to create a set of questions for each topics using labview. So Is there any way that i can match certain word in the string to make sure that answer is correct? Cause i'm sure that every user that input answer will be different. Thus, I want to pick out main point as an answer. Is there anyway i can do it?? 
    Really appreciate your help!!! 
    Thank you!! 
    Solved!
    Go to Solution.
    Attachments:
    Match Strings.vi ‏8 KB
    Match Strings.vi ‏8 KB

    Here's another option (building on Jeff's code).  Turn on the Conditional Terminal on the FOR loop and change it to "Continue if TRUE".  This way, the loop will exit as soon as a failure is found.  Just pass the result straight out of the loop.  If none fail, then the FOR loop will exit on its own (from the auto-indexing) and a pass is passed out.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Match String.png ‏19 KB

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

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

  • Match ANY word

    Is there a way to match ANY word in a string using CONTAINS?
    - e.g. Given a set of columns holding variations of text borrowed from above
    'you can optionally edit your post'
    'you can optionally preview your post'
    'you can optionally delete your post'
    and then match all 3 with something syntactically like
    and CONTAINS(<column>, 'optionally % your post') >0
    I predict using % is a bad idea as expansion will kill it as the index grows, but is there an alternative that will match a single word gap (so not using NEAR)?

    Although not intended for the purpose, using a stopword has the effect of requiring that it match any word. You could use an existing stopword like "the" or you could create your own stoplist and your own stopword for the purpose like "anyword", as demonstrated below. The stopword is not indexed, but its location is recorded, so a word must be present in that spot. I suspect it might be faster than % or NEAR or other methods.
    SCOTT@orcl_11gR2> CREATE TABLE test_tab
      2    (test_col  VARCHAR2(60))
      3  /
    Table created.
    SCOTT@orcl_11gR2> INSERT ALL
      2  INTO test_tab VALUES ('you can optionally edit your post')
      3  INTO test_tab VALUES ('you can optionally preview your post')
      4  INTO test_tab VALUES ('you can optionally delete your post')
      5  INTO test_tab VALUES ('some other data')
      6  SELECT * FROM DUAL
      7  /
    4 rows created.
    SCOTT@orcl_11gR2> BEGIN
      2    CTX_DDL.CREATE_STOPLIST ('test_stoplist', 'BASIC_STOPLIST');
      3    CTX_DDL.ADD_STOPWORD ('test_stoplist', 'ANYWORD');
      4  END;
      5  /
    PL/SQL procedure successfully completed.
    SCOTT@orcl_11gR2> CREATE INDEX test_idx
      2  ON test_tab (test_col)
      3  INDEXTYPE IS CTXSYS.CONTEXT
      4  PARAMETERS ('STOPLIST test_stoplist')
      5  /
    Index created.
    SCOTT@orcl_11gR2> SELECT token_text FROM dr$test_idx$i
      2  /
    TOKEN_TEXT
    CAN
    DATA
    DELETE
    EDIT
    OPTIONALLY
    OTHER
    POST
    PREVIEW
    SOME
    YOU
    YOUR
    11 rows selected.
    SCOTT@orcl_11gR2> SELECT * FROM test_tab
      2  WHERE  CONTAINS (test_col, 'optionally ANYWORD your post') > 0
      3  /
    TEST_COL
    you can optionally edit your post
    you can optionally preview your post
    you can optionally delete your post
    3 rows selected.

  • Replacing first Character of every word in a string with an Uppercase

    Hi,
    Is it possible to replace all first character of every word in a string with UpperCase?
    $="autocad lite"
    Should look "Autocad Lite" .
    Thanks,
    François

    Hi FRacine,
    Please refer to the script below:
    $givenname="autocad lite"
    $givenname
    $givenname = $givenname.substring(0,1).toupper()+$givenname.substring(1)
    $givenname
    Edit: to change first character in every word, please refer to this script, this may not be the best way, but it can work:
    $givenname="autocad lite"
    $givenname
    $words=$givenname.split(" ")
    $givenname=""
    foreach ($word in $words){
    $givenname+=$word.substring(0,1).toupper()+$word.substring(1)+" "}
    $givenname=$givenname.trim()
    $givenname
    If there is anything else regarding this issue, please feel free to post back.
    Best Regards,
    Anna Wang

  • In "Match First String", 13 is matched with 1

    I find a weird thing with "Match First String".
    with a string array holding '1', '3', '13', the index for string '13' is 0. is there any revised version of String match available?  thanks.

    I cannot see the problem.
    Please attach a small program containing useful defaults in all controls.
    Let us know
    What you get as result
    What you expect as result.
    I believe that if you have an arrray containing the strings [1,3,13] and a string of "13", 0 is the correct index result. Is that what you are doing?
    (Element 0 of the array is the first element that matches the beginning of "13" (the "1"!), so the output string="3" and index=0.)
    LabVIEW Champion . Do more with less code and in less time .

  • [solved]zsh history completion not matching after first word?

    Hi!
    I just switched to zsh some days ago and I can't get the history search completion working like it's used to work with bash (history-search-backward /  history-search-forward)
    I installed grml-zsh-config, tried to rewrite most of my .bashrc to work with zsh... read a lot of man pages and changed some settings (and broke some random things... and un-broke most of them again)...
    Now when I enter p.e.:
    $ sudo tes
    ...and press the up/down arrows, it keeps the "sudo" but not the "tes" - it goes trough all commands that I called with sudo. Seems to behave the same way for other commands - keeps the first word, ignores everything else I typed.
    No idea what this is called, what it's good for or how to change it.
    Where do I look for this?
    Last edited by whoops (2012-12-01 19:09:52)

    ^ I've not used that, so I can't say whether or not my solution is better or worse. However, I suggest using "up-line-or-beginning-search"/"down-line-or-beginning-search", as described in zshall:
    up-line-or-beginning-search, down-line-or-beginning-search
    These widgets are similar to the builtin functions up-line-or-search and
    down-line-or-search: if in a multiline buffer they move up or down within the buf‐
    fer, otherwise they search for a history line matching the start of the current
    line. In this case, however, they search for a line which matches the current line
    up to the current cursor position, in the manner of history-beginning-search-back‐
    ward and -forward, rather than the first word on the line.
    From my .zshrc:
    autoload up-line-or-beginning-search
    autoload down-line-or-beginning-search
    zle -N up-line-or-beginning-search
    zle -N down-line-or-beginning-search
    bindkey "\e[A" up-line-or-beginning-search
    bindkey "\e[B" down-line-or-beginning-search

  • Get first word in string containing '-' using T-SQL

    I'm trying to update a column in a table by inserting the first word (that has hyphen) in another column.  I'm trying this:
    UPDATE DSoil
    SET SoilName column = first word of MapUnit column (Only if the first word has '-' character).
    Appreciate any help.
    Marilyn Gambone

    DECLARE @myTable TABLE (MapUnit Varchar(100), SoilName Varchar(100) Null)
    INSERT INTO @myTable (MapUnit)
    VALUES ('Test'), ('test-1'), ('-abc test')
    UPDATE @myTable
    SET SoilName = (CASE WHEN CHARINDEX('-', MapUnit) <> 0 THEN SUBSTRING(MapUnit, 1, (CASE WHEN CHARINDEX(' ', MapUnit) = 0 THEN LEN(MapUnit) ELSE CHARINDEX(' ', MapUnit) END)) ELSE SoilName END)
    SELECT * FROM @myTable
    --output
    MapUnit SoilName
    "Test" NULL
    "test-1" test-1
    "-abc test" -abc
    Best Wishes, Arbi; Please vote if you find this posting was helpful or Mark it as answered.

  • Regex - match a word except when it's preceeded by another word

    Does anyone know how to write a regular expression that will match an occurrence of a word except when it's preceeded by another word? I'm trying to match all occurrences of the word "function" except when it's part of the phrase "end function". Is that possible in a single regular expression?

    Maybe this is just how it works, but I'm not sure why a string
    with one space wouldn't match but a string with two would.At the beginning of the spaces, the lookbehind causes the match to fail, but then the Matcher bumps ahead one position and tries again. At that point, the lookbehind expression doesn't apply anymore, so you get a match. (You should be able to confirm this by counting the spaces in your output.) I tried using the "aggressive plus" to force it to treat all the spaces as one atom, but that didn't work:
      Pattern p = Pattern.compile("(?<!end)(\\s++)function");I don't see how to do this using "pure" lookaround, but if you don't mind matching the preceding word, this will work:
      Pattern p = Pattern.compile("(^|(?!end\\b)\\b\\w+ +)function\\b",
                                  Pattern.MULTILINE);Getting pretty hairy, I know, but it matches the word "function", either as the first thing on the line, or preceded by a word that is not "end" (those first couple of \b's are there to ensure that only the whole word "end" will block the match). Here's how you would use this pattern to replace "function" with "method", except when it's preceded by "end":
    import java.util.regex.*;
    public class Test
      public static void main(String[] args)
        String target = "end function\n"
                      + "function test\n"
                      + "functioning test\n"
                      + "test function\n"
                      + "test function end\n"
                      + "end    function\n"
                      + "ending function\n"
                      + "rend   function\n"
                      + "end   functioning\n";
        Pattern p = Pattern.compile("(^|(?!end\\b)\\b\\w+ +)function\\b",
                                    Pattern.MULTILINE);
        Matcher m = p.matcher(target);
        target = m.replaceAll("$1method");
        System.out.println(target);
    }Here's the output I get:
    end function
    method test
    functioning test
    test method
    test method end
    end    function
    ending method
    rend   method
    end   functioningOf course, if you do know that there will always be exactly one space between "end" and "function", none of this is necessary; you can just use dcostakos's original lookbehind regex--except that I would add word boundaries:
    Pattern p = Pattern.compile("(?<!end\\s)\\bfunction\\b");

  • 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

  • Query only works on the first word of the managed property

    I have several managed properties that are not returning query results as expected, they are returning results only if the term queried matches
    the first word in the property, any other query returns no results.
    Scenario:
    filename = "Sample Excel File.xlsx" (OOTB property)
    FooOwner = "Martin Zima"
    FooSiteName = "Test Site"
    If I query filename:Sample, filename:File, filename:Excel (or any combination) they all works as expected. However, if I query "FooOwner:Martin"
    it works, but if I query FooOwner:Martin Zima it fails, and FooOwner:Zima also fails. Similarly, if I search for FooSiteName:Site it fails (only CPSiteName:Test works). Everything seems ok in the crawled property and managed property. Can anyone please help?

    Hi Martin,
    I tried in my envrionment, author:"Rebecca Tu" and
    author:Rebecca Tu returned the same result. Please try author:* and see if it will return all the results. If there is no result, then we should check the DisplayAuthor property in Search schema.
    In the default search result page, there should be Author refiner in the Refinement. You could use the default one as below:
    Regards,
    Rebecca Tu
    TechNet Community Support

  • Reading first word from text file

    Hello all,
    I created a program which I can type in a line and store it into a file. What I need my next program to do is read and display just the first word from each line on the text file.
    Here is what I have:
    import java.io.*;
    public class ReadFromFile
    public static void main (String args[])
         FileInputStream firstWord;          
              try
                  // Open an input stream
                  firstWord = new FileInputStream ("FileofWords.txt");
                  // Read a line of text
                  System.out.println( new DataInputStream(firstWord).readLine() );
                  // Close our input stream
                  firstWord.close();          
                   System.err.println ("Unable to read from file");
                   System.exit(-1);
    }

    what i would like is my program to get the first word of every line and put it in my array.
    This is what i have attempted.
    import java.io.*;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    public class testing {
         String[] tmp = new String [2];
         String str;
         public void programTest()
              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();
    }//end classAny help is most appreciated

Maybe you are looking for

  • Cant install hl 1450 printer on 10:6:8

    problem installing drivers hl1450 printers on 10:6:8

  • Fmb2xml

    Hello everybody! I've just read a preview to APEX 3.2 and conversion forms to APEX. It was said that you need xml from your forms before starting migration. I'm still using forms6i and I've found the hint to use fmb2xml. But I can't find this program

  • Import catalogue from adobe photoshop elements

    How can I import a photo catalogue from adobe photoshop elements (9.0) into Aperture? Thanks for every hint, Penibel

  • "iTunes couldn't connect to this iPad. Can't establish a secure connection to the device."

    Hello anyone this might concern, I'm having a  problem with my week-old iPad 3 WiFi + 4G (although not 4G in Sweden, but anyway). When I yesterday (19th of June 2012) tried to hook my iPad to my mid 2011 iMac 27" wanting to synchronize it, I got a wa

  • Problems with FaceTime and iMessage

    My iPad mini isn't letting me log into iMessage or FaceTime. It asks for my Apple ID and I enter it but then it says "an error occurred during activation. Please try again." I'm getting very stressed and I really don't want to get a whole new device.