How to match the nth word in a string?

Hi, when I have a string like
"AA BBBB CCC DDDDDD EEE FF"
all words are of the form \w+
and I'd like to match the nth word, for example the third would be "CCC",
how can I establish this with just one regular expression?
Some annotations:
This is done with Java 1.4, but tools like the string tokenizer are not
possible (restrictions of the application) We're limited to one regular expression!
In Perl, one would do it this way:
This would be the regular expression:
"[\w+\s+\w+\s+](w+)"
and with the help of $1, you might match the first paranthesis.
As I said before, this is no solution here, because we're limited to one
regular expression
Another idea for Java Regex would be to define a positive lookahead, like (?<=\w+\s+\w+\s+), but as the width of it is variable, it is not allowed!
Thanks for your help,
Heiko Kubidsky

well, i did another test class
import java.util.regex.*;
public class NthMatch {
public static void main(String[] args) {
  Pattern p = Pattern.compile(
    "(?:\\w+\\s+){" + args[1] + "}(\\w+)(?:\\s.*)?");
  Matcher m = p.matcher(args[0]);
  if (m.matches())
   System.out.println(m.group(1));
  else
   System.out.println("no match");
}run: java NthMatch "aa bb cc dd" 2
does that help?
what kind of framework you have to squeese the regex in?
what do you want to do with that regex?
do you want to check if Nth word maches something, or do you want to retriev that Nth string? or are you trying to do anything else?
your explanation is unfortunatelly not sufficient :(

Similar Messages

  • 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

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

  • How to translate the key words in ABAp program from lower case to upper cas

    How to translate the key words in ABAp program from lower case to upper case?

    Hi Kittu,
    You need to set the Pretty Printer settings to achieve key words in ABAP program from lower case to upper case.
    Utilities -> Settings -> Pretty Printer (tab) -> Select third radio button.
    Thats all.
    <b>Reward points if this helps.
    Manish</b>

  • How do obtain the number words typed in a Pages document?

    How do obtain the number words typed in a Pages document?

    I found it!  To get the number of words in my Pages 5.1 document...I clicked on the paper-icon on the far left...(at the very left edge) it gave me a selection that ended with "count words."  TaDa!  Thanks

  • KeywordQuery is matching the whole word

               
    hi
    i am using Microsoft.SharePoint.Client.Search. The search works fine except the thing that is matching the whole word.
    For example if i search for the word gips i get hits back,  but if i search only gip i don't get any results back. Is there a way to avoid this behavior?
    KeywordQuery kq = new KeywordQuery(kq.QueryText = text + " AND path:\"" + path + "\"";
    kq.TrimDuplicates = false;
    SearchExecutor searchExecutor = new SearchExecutor(context);
    ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(kq);
    context.ExecuteQuery();

    Try appending the wildcard character "*" (without the quotes) to the query.
    Start here:  http://benprins.wordpress.com/2013/03/13/sharepoint-2013-search-tips-and-tricks/
    I trust that answers your question...
    Thanks
    C
    |
    RSS |
    http://crayveon.com/blog |
    SharePoint Scripts | Twitter |
    Google+ | LinkedIn |
    Facebook | Quix Utilities for SharePoint

  • How to display the MS word, powerpoint  document in portal?

    Hi,
    How to display the MS word, powerpoint  document in portal?
    Regards,
    MrChowdary

    Hi Chowdary,
      I think, you can't do this using iview templates.  But you can do this using portal component iview.  For that, you have to write one java program which should read the contents of the input file and displays in the internet browser itself.
    Regards,
    Venkatesh. K
    /* Points are Welcome */

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

  • To extract the last word in a string

    Hi
    I am using BODS 14.1.1.210 
    I would like to extract the last word in a string in BODS query. How can I achieve this when  I don't know how many words are present in a space delimited string.
    Example
    Input                                              Output    
    My name is Tim                              Tim
    Complicated                                    Complicated
    there is a bird in the nest                 nest
    Please let me know if there is a query function for this one.
    Cheers!

    Hi,
    try this-
    word_ext(fieldname,-1,' ')
    Atun

  • Find the nth occurrence of a string in a string

    Hi,
    I'm wondering if there is a method like indexOf, but finds the nth occurrence of a string
    public static int occurrence(java.lang.String str,
                                 java.lang.String toFind,
                                 int occurrence)Cheers
    Jonny

    phdk wrote:
    calypso was refering to promes pseudo code.What is promes? I don't understand the word. Sorry!
    I put the global variable 'count' now in the method occurence
    public static int occurence(String str, String toFind, int occurence){
            int origLength = str.length();
            int count = 0;
            while(str.length()>0){
                str = contains(str, toFind, count);
                   if(count == occurence){
                    int length = str.length();;
                    int actualPos = origLength-(length+1);
                    return actualPos;
                   count++;
            return -1;
    public static String contains(String str, String toFind, int count){
            int occurence = str.indexOf(toFind);
            if(occurence != -1 ){
                 count = count+1;
                return str.substring(occurence+1,str.length());
            }else{
                return "";
      }The output is 1 position to high.
    I still don't get which part of the code to replace with this pseudo code: s'.indexOf('toFind', 'index'+1)
    Sorry for being dimwitted!
    Thanks
    jonny

  • How to find the exact word in a long text?

    Hi,
    Scenario:
    I have long text containing the system status of the equipment.
    Issue:
    I need to find the exact word from the list of the statuses. I have tried to use the FIND keyword but it does not work for all the cases.
    Example:
              FIND 'REL' IN <status_list> IGNORING CASE.
              if sy-subrc = 0.
              " do something
              endif.
    If the status list contains the word 'RELR', the sy-subrc is set to 0 (which may be because it searches the list based on a pattern) but I want to get the exact match.
    Can anybody suggest me on this.
    Regards
    s@k

    >
    siemens.a.k wrote:
    > Dear Kiran, Vasuki,
    >
    > The data type of status list is char with length 40.
    > The status list:
    >
    > Case 1: list -  REL  MANC NMAT PRC  SETC
    > FIND 'REL ' IN <status_list> IGNORING CASE
    > the sy-subrc is set to 0
    >
    > Case2: list - CRTD MSCP NMAT PRC  RELR SETC
    > FIND 'REL ' IN <status_list> IGNORING CASE
    > the sy-subrc is still set to 0 even though the list does not contain the word 'REL'
    >
    > I have also tried using
    > if <status_list> CS 'REL'
    > and
    > if <status_list> CS 'REL '
    >
    >
    > Please do let me know if I am anyway unclear about issue...:)
    >
    > Regards
    > s@k
    This is becacuse when you check
    > Case2: list - CRTD MSCP NMAT PRC  RELR SETC
    It is having RELR so that is the reason you are getting subrc = 0.
    >Ok try CS it should work perfectly.
    It seems... CS also not the correct answer
    (It will count RELR)  below thread sachin is correct ...Do that way ....
    Regards
    sas
    Regards
    Sas
    Edited by: saslove sap on Jan 25, 2010 6:58 AM

  • Automatic creation of customer from BP  - How to match the fields? CVI

    I am trying to create a customer from a BP. I am done all the customizing steps.
    Now I need to match the fields.
    There is an error message with this field KNA1-SPRAS that doenst match
    what should I do?
    I have read this "In particular you have matched the required entry fields. You have to set all fields that are required entry fields in the customer/vendor account as required entry fields in the field selection control for your customer/vendor business partner roles."
    Where do I set these fields and how do I know which fields to set?
    Thank you for your help.

    Hi,
    I am trying to create a customer. I am done all the customizing steps.
    Which steps do you follow to create? Please give me the details. Thanks.
    After customizing, I created the business partner using the BP transaction. In the syncronizationcockit I still have errors messages when I select BP->Customer and then give the BP number. How should I do this correctly. Please if possible a screenshot will be good.
    I have an error message that a field information is missing. I filled the field but still have the same error.
    Thanks.

  • How to hide the MS Word Web App in SharePoint Online Document Library

    Hi Guys!
    Badly needed your input on this scenario. I've created a document library in
    SharePoint Online but when I add a document I wanted the MS Word Web App toolbar
    to be hidden as I didn't want to have the document printed  and downloaded. Just want to have the file in read only mode.
    I've come across subscription to IRM of Office 365 as a solution but it's kinda expensive for this need.
    Any idea on how to resolve this scenario would be greatly appreciated.
    Thanks,
    Venus

    Hi!
    Even if I give a view-only permission to the user, still the print button is available and the document can still be downloaded to PDF file.
    Also, the permission rights given to the users of the document library is contributor. But after routing for approval and the content is approved. It should be read-only even to the one who authored the document.
    I've checked also IRM for a solution but unfortunately what we have is E1 package so IRM is out of the option.
    Thanks,
    Venus

  • How to maintain the nth and the (n-1)th version of my application

    Folks
    I would like to maintain the nth and the (n-1)th version of my application. Thus if there is any error with the nth version, people can switch back to the older version. Can anyone tell me how I can maintain this ?
    thanks
    venkat

    Thanks for your reply. I still have some questions. Lets say that I have two jnlp files, current and "last stable". The jar href tag in the jnlp file should point to the application correct ?. If we have two different jar files, wont webstart treat it as two different applications ? We will have both "n" and "n-1" version of the application locally cached on the client. My objective is to have only one version, either the nth or the (n-1)th version. How is this possible ? your help is greatly appreciated

  • Match the given word with dictionary

    Hi all
    I have an issue .
    I need to check the given word from the user input is a dictionary word or not.
    if it is a dictionary word then i am doing some functionality.
    how can i do that?
    thanx in advance

    Load a dictionary of words into a Map of some sort. Use the user's word as the key into the map - if the map returns null, then it can be assumed to not be a real word. You will probably want to provide some mechanism so that the user can populate the map with proper names and other stuff that's not in the dictionary.
    To obtain a (raw text) dictionary with which to populate the Map you could look at the files in the /usr/share/dict folder on most Linux systems. If you don't have one to hand you can probably obtain and download one with a bit of Googling.

Maybe you are looking for

  • Package javax.servlet does not exist

    Trying to learn servlets. just installing software & tesing install. What I have done: 1. read Deitel text, and written & tested applications and applets..even on my web site. surprise surprise. 2. installed J2Std Edition and did applications & apple

  • Image rendering in flash

    We are building a flash based product where we need to create icons for various modules. we are having challenges in look and feel of the icons- what looks really good on Adobe Illustrator/ Photoshop looks jagged on flashPlayer. A challenge we have i

  • Narrowing Edit Permissions

    Edit is a permission required for certain groups for entering metadata when uploading documents. This permission also allows members of this group to edit site pages. I need to disable editing of site pages while keeping permission to enter metadata.

  • Sles11 named as OES2-Backup-DNS?

    Hi, I was wondering if it would be possible to use the named service of a Sles11 to work as a backup server for our OES2 DHCP/DNS setup? I mean, novell-named is not all that different to the default Linux one, right? If so, how would I go about doing

  • Error 800003 on ipad 2

    Whenever I try syncing my iPad on my desktop, there's an "Error 0x8000003" that shows up. It's been a couple of days since this first showed up. I also tried syncing it on my laptop and it worked.. How to I fix this? Help! Thanks!