How to make regex alternation return first match?

Hi,
I have the following string:
"i am a man and i have a cat and a dog and a bird"
and I wish to extract the part of the sentence from "man" up to the first occurence of "dog" or "cat". So I wish the extracted sentence to be
"and i have a"
or alternatively
"man and i have a cat"
I would guess the regular expression "man.*(cat|dog)" should do it, but that seems to always return the sentence up to the last occurrence of dog and cat, when I want the first occurrence. So "man.*(cat|dog)" returns (when using find() and group()):
"man and i have a cat and a dog"
Anyone have any ideas how I can return the sentence from (preferably excluding) man and to (preferably excluding) the first occurrence of cat or dog?
Thanks!
Message was edited by:
MagnusGJ
Message was edited by:
MagnusGJ

Take your pick -
        // One  possibility
        String target = "i am a man and i have a cat and a dog and a bird";
        String result = target.replaceFirst(".*?man (.*?)( cat| dog).*", "$1");
        System.out.println(result);
        // and another
        Matcher m = Pattern.compile("man (.*?) (cat|dog)").matcher(target);
        if (m.find())
            System.out.println(m.group(1));
        }

Similar Messages

  • How to make a function return number(10,0) data type (ORACLE 10g)?

    With 10g, how to make a function return number(10,0) data type?
    here is the function, it returns a number type :
    create or replace FUNCTION Get_portfolio_Id3 (p_HistObjTable In Varchar2,p_LHISTOBJID IN NUMBER) RETURN view_cpu_STD_Asset.LPORTFOLIOITEMID%Type IS
    v_Id view_cpu_STD_Asset.LPORTFOLIOITEMID%Type;
    BEGIN
    If p_HistObjTable ='amPortfolio'
    then v_Id:=p_LHISTOBJID ;
    elsIf p_HistObjTable = 'amComputer' then
    select litemid into v_Id from smcdba.amComputer c where c.LCOMPUTERID=p_LHISTOBJID ;
    else v_Id:=-99;
    End If;
    RETURN v_Id;
    END Get_portfolio_Id3;
    Thanks.
    Message was edited by:
    user631701

    create or replace FUNCTION Get_portfolio_Id3 (p_HistObjTable In Varchar2,p_LHISTOBJID IN NUMBER) RETURN view_cpu_STD_Asset.LPORTFOLIOITEMID%Type IS
    v_Id view_cpu_STD_Asset.LPORTFOLIOITEMID%Type;
    BEGIN
    If p_HistObjTable ='amPortfolio'
    then v_Id:=p_LHISTOBJID ;
    elsIf p_HistObjTable = 'amComputer' then
    select litemid into v_Id from smcdba.amComputer c where c.LCOMPUTERID=p_LHISTOBJID ;
    else v_Id:=-99;
    End If;
    RETURN round(v_Id);
    END Get_portfolio_Id3;

  • How to make a Carriage Return in a Word-Table by OLE Automation

    I generated a Table in a Word-Document by using the OLE2 Interface.
    After that I wrote a Text in the first cell of the table.
    Now I want to make a Carriage Return to write another Textline in the same Cell.
    But first i must move the cursor to the end of the Text.
    I haven't already figured that out.
    Can someone Help me?
    I tried this but then the Cursor moves to the Begin of the second Cell in the same row.
    *Writing the Text in the Cell
      GET PROPERTY OF o_cell 'Range' = o_range.
      SET PROPERTY OF o_range 'Text' = wa_anschr-ename.
    *Move Cursor
      GET PROPERTY OF o_cell  'Range' = o_range.
      GET PROPERTY OF o_range 'End' = ld_pos.
      SET PROPERTY OF o_range 'Start' = ld_pos.
      CALL METHOD OF o_range ' Select'.

    I don't know about your suggestion.
    I solved the Problem with that Method:
    CALL METHOD OF o_selection 'EndKey'
        EXPORTING
          #1 = '5'.
      CALL METHOD OF o_selection 'TypeParagraph'.
    The Parameter "5" ist the VB Constant wdline...
    Now it works and I'm happy

  • How to Make FUNCTION to return multiple column and multiple row output

    Hi All,
    Kindly Share ur Idea;Thanks in Advance;
    i Have Table Demo.
    table DEMO:
    id name
    1 a10
    1 a11
    1 a12
    2 b10
    2 b11
    3 ccc
    and the function is like:
    create or replace function (p1 number) return varchar2 as
    vid number;
    vname varchar2(20);
    begin
    select id,name into vid,vname from demo where id=p1;
    return v1;
    end;
    this function returns output for id=3;
    BUT,
    i need output as (for input as 1)
    vid vname
    1 a10
    1 a11
    1 a12

    A function returns a single datatype.
    That datatype may be an atomic datatype (varchar2, number etc.) or it may be an object/record datatype, or even a collection datatype.
    Where are you going to use this function? In PL/SQL or SQL?
    If you are wanting to use it in SQL, then you would need a pipelined function e.g.
    SQL> CREATE OR REPLACE TYPE myemp AS OBJECT
      2  ( empno    number,
      3    ename    varchar2(10),
      4    job      varchar2(10),
      5    mgr      number,
      6    hiredate date,
      7    sal      number,
      8    comm     number,
      9    deptno   number
    10  )
    11  /
    Type created.
    SQL> CREATE OR REPLACE TYPE myrectable AS TABLE OF myemp
      2  /
    Type created.
    SQL> CREATE OR REPLACE FUNCTION pipedata(p_min_row number, p_max_row number) RETURN myrectable PIPELINED IS
      2    v_obj myemp := myemp(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
      3  BEGIN
      4    FOR e IN (select *
      5              from (
      6                    select e.*
      7                          ,rownum rn
      8                    from (select * from emp order by empno) e
      9                   )
    10              where rn between p_min_row and p_max_row)
    11    LOOP
    12      v_obj.empno    := e.empno;
    13      v_obj.ename    := e.ename;
    14      v_obj.job      := e.job;
    15      v_obj.mgr      := e.mgr;
    16      v_obj.hiredate := e.hiredate;
    17      v_obj.sal      := e.sal;
    18      v_obj.comm     := e.comm;
    19      v_obj.deptno   := e.deptno;
    20      PIPE ROW (v_obj);
    21    END LOOP;
    22    RETURN;
    23  END;
    24  /
    Function created.
    SQL> select * from table(pipedata(1,5));
         EMPNO ENAME      JOB               MGR HIREDATE                    SAL       COMM     DEPTNO
          7369 SMITH      CLERK            7902 17-DEC-1980 00:00:00        800                    20
          7499 ALLEN      SALESMAN         7698 20-FEB-1981 00:00:00       1600        300         30
          7521 WARD       SALESMAN         7698 22-FEB-1981 00:00:00       1250        500         30
          7566 JONES      MANAGER          7839 02-APR-1981 00:00:00       2975                    20
          7654 MARTIN     SALESMAN         7698 28-SEP-1981 00:00:00       1250       1400         30
    SQL> select * from table(pipedata(6,10));
         EMPNO ENAME      JOB               MGR HIREDATE                    SAL       COMM     DEPTNO
          7698 BLAKE      MANAGER          7839 01-MAY-1981 00:00:00       2850                    30
          7782 CLARK      MANAGER          7839 09-JUN-1981 00:00:00       2450                    10
          7788 SCOTT      ANALYST          7566 19-APR-1987 00:00:00       3000                    20
          7839 KING       PRESIDENT             17-NOV-1981 00:00:00       5000                    10
          7844 TURNER     SALESMAN         7698 08-SEP-1981 00:00:00       1500          0         30
    SQL> select * from table(pipedata(11,15));
         EMPNO ENAME      JOB               MGR HIREDATE                    SAL       COMM     DEPTNO
          7876 ADAMS      CLERK            7788 23-MAY-1987 00:00:00       1100                    20
          7900 JAMES      CLERK            7698 03-DEC-1981 00:00:00        950                    30
          7902 FORD       ANALYST          7566 03-DEC-1981 00:00:00       3000                    20
          7934 MILLER     CLERK            7782 23-JAN-1982 00:00:00       1300                    10
    SQL>If you are using it in PL/SQL then just populating a collection datatype and returning that will do. Though you should question why you want to pass large amounts of data around like that first.
    Explain your purpose and what you are intending to do and we can recommend the best way.
    {message:id=9360002}

  • How to make set up with first call of method of a custom class?

    Hello
    I have build a custom class with a few custom methods.
    Method1 is called per every record of internal table. I need to set up certain parameters tha are the sme for all the calls  (populate the range , to fill the internal table , etc). This should be done only once.
    call method ZBW_CUSTOM_FUNCTIONS=>METHOD1
            exporting
              I = parameter1
            importing
              O = parameter2.
    Loop at ....
       <itab>-record1 = parameter2
    endloop.
    Methods2, 3 , 4 dont need any set up.
    Can somebody tell me how to do it within class?
    Thanks

    Instance methods (as opposed to static methods) are called on an object, which is an instance of a class. Broadly, think of the class as a template for the creation of objects. The objects created from the class take the same form as the class, but have their own state -- their own attribute values. In pseudo-ABAP (this won't even close to compile), let's say you have the following class:
    CLASS cl_class.
         STATICS static_attr TYPE string.
         DATA attr1 TYPE string.
         DATA attr2 TYPE i.
         CLASS-METHOD set_static_attr
              IMPORTING static_attr TYPE string.
              cl_class=>static_attr = static_attr.
         ENDMETHOD.
         METHOD constructor
              IMPORTING attr1 TYPE string
                                 attr2 TYPE i.
              me->attr1 = attr1.
              me->attr2 = attr2.
         ENDMETHOD.
         METHOD get_attr1
              RETURNING attr1 TYPE string.
              attr1 = me->attr1.
         ENDMETHOD.
    ENDCLASS.
    When you create an instance of the class (with CREATE OBJECT oref), the constructor is implicitly called. You can pass parameters to the constructor using: CREATE OBJECT oref EXPORTING attr1 = 'MyString' attr2 = 4.
    You then call methods on the instance you have created. So, oref-&gt;get_attr1( ) would return 'MyString'.
    The constructor is called when the object is created (so, when you call CREATE OBJECT). At this time, the setup is done, and any subsequent methods you call on the object will be able to use the attributes you set up in the constructor. Every object has its own state. If you had another object, oref2, changing its instance attribute values would not affect the values of oref.
    Static methods and attributes are different. A static attribute exists only once for all instances of the class -- they share a single value (within an internal session, I think. I'm not sure of the scope off-hand.) You also call static methods on the class itself, not on instances of it, using a different selector (=&gt; instead of -&gt;). So, if you called cl_class=&gt;set_static_attr( static_attr = 'Static string' ), 'Static string' would be the value of static_attr, which belongs to the class cl_class, and not instances of it. (You can also set up a class constructor, which is called when the class is loaded, but that's another subject.)
    To answer your question more succinctly: no, the constructor is not called before each method. It is only called when you create the object. Any subsequent methods called on the object can then access its attributes.
    Please have a look at [http://help.sap.com/saphelp_nw70ehp2/helpdata/en/48/ad3779b33a11d194f00000e8353423/frameset.htm] for a more thorough treatment of basic object concepts. (The rest of that documentation is very thin, but it'll get you started. Also, it doesn't appear to deal with statics. You'll have to look elsewhere for that.)

  • How to make apdu.getBuffer() return buf that is greater than 133 bytes.

        public void process(APDU apdu) {
          byte[] buf = new byte[256];
            buf = apdu.getBuffer();
            // GOOD PRACTICE: RETURN 9000 ON SELECT
            if (selectingApplet()) {
                return;
            apdu.setIncomingAndReceive();
            switch (buf[ISO7816.OFFSET_INS]) {
                case (byte) 0x01:
    This is my process method. I have a command APDU of length 200 bytes that I want the buffer to read and store into a local byte array. However, apdu.getBuffer() is only grabbing the first 133 bytes of data.
    According to javadocs:
    "The APDU object is owned by the Java Card runtime environment. The APDU class maintains a byte array buffer which is used to transfer incoming APDU header and data bytes as well as outgoing data. The buffer length must be at least 133 bytes ( 5 bytes of header and 128 bytes of data ). The Java Card runtime environment must zero out the APDU buffer before each new message received from the CAD."
    Since the buffer length is larger than 133 bytes, why does it not accept the remaining bytes?
    I am using jCardSim on NetBeans IDE, java card version 2.2.2.
    Also, could someone explain to me what exactly apdu.setIncomingAndReceive() does? My code is able to build/run both with and without it.
    Thanks

    I tried using that in my code, but it's still not working, I must be placing it in the wrong spot. I put it in the process method right before my switch cases. Do I actually put all of the code in the while loop? Perhaps you could explain the code to me, why do you only want the last two bytes of LC, and why 55? This is what it looks like currently:
        public void process(APDU apdu) {
            byte[] buf = apdu.getBuffer();
            // GOOD PRACTICE: RETURN 9000 ON SELECT
            if (selectingApplet()) {
                return;
           short bytesLeft = (short) (buf[ISO7816.OFFSET_LC] & 0x00FF);
            if (bytesLeft < (short) 55) {
                ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
            short readCount = apdu.setIncomingAndReceive();
            while (bytesLeft > 0) {
                // process bytes in buffer[5] to buffer[readCount+4]; 
                bytesLeft -= readCount;
                readCount = apdu.receiveBytes(ISO7816.OFFSET_CDATA);
            // HARDCODED PARAMETERS TO PASS INTO FUNCTIONS
            byte[] O = new byte[6];
            byte[] U = new byte[3];
            byte[] N = new byte[5];
            byte[] A = new byte[4];
            Util.arrayCopy(buf, (short) (ISO7816.OFFSET_EXT_CDATA), O, (short) 0, (short) 6);
            Util.arrayCopy(buf, (short) (ISO7816.OFFSET_EXT_CDATA + 7), U, (short) 0, (short) 3);
            Util.arrayCopy(buf, (short) (ISO7816.OFFSET_EXT_CDATA + 11), N, (short) 0, (short) 5);
            Util.arrayCopy(buf, (short) (ISO7816.OFFSET_EXT_CDATA + 17), A, (short) 0, (short) 4);
            switch (buf[ISO7816.OFFSET_INS]) {
                case (byte) 0x01:
                    // CALL FUNCTION  R
                    byte[] b = R(O, U, N, A);
                    // PRINT B
                    apdu.setOutgoing();
                    apdu.setOutgoingLength((short) b.length);
                    apdu.sendBytesLong(b, (short) 0, (short) b.length);
                    break;
                case (byte) 0x02:
                    byte[] k2 = new byte[(short) 176];  
                    //29 is the offset in the command apdu that contains the parameter data
                   // THIS IS THE LINE THAT THE CODE FAILS AT - SINCE IT CAN ONLY READ 133 BYTES OF DATA, IT CAN'T ARRAY COPY 176 BYTES OF DATA FROM buf
                    Util.arrayCopy(buf, (short) 29, k2, (short) 0, (short) 176);
                    byte[] a = S(k2, O, U, N);
                    // PRINT a
                    apdu.setOutgoing();
                    apdu.setOutgoingLength((short) a.length);
                    apdu.sendBytesLong(a, (short) 0, (short) a.length);
                    break;

  • Workflow task process participants in serial order: how to make it stop at first rejection

    I have listed 3 participants as task process participants in serial order on my approval process. Currently even if the first one rejects, it moves on to the next one and then next no matter if they reject or approve it. The final outcome is rejected if
    anyone of them reject it.
    Is there a way to stop the workflow and mark the workflow status as rejected if anyone of the participants mark it as rejected?

    Hello All,
    i have read the article
    http://office.microsoft.com/en-us/sharepoint-designer-help/understand-approval-workflows-in-sharepoint-2010-HA101857172.aspx#_Toc264526218 but could not find anywhere a step by step process to End workflow on first rejection in Designer 2010.
    Can you please help me the steps in SP2010 for setting the Workflow Status as Rejected on the first Rejection itself?
    Thanks,
    Shubhangi
    $hubhangi

  • How to make reader.ready() return false

    reader.ready() method returned false for me when reading from
    when reader is obtained from databse. eg. Clob reader.
    So that can be acceptable that next call may block thats why ready() returned false.
    But i want to simulate situation when reader.ready() returns false even if reader is eg. FileReader, directy reading from
    existing file on local unix machine. (and this file is having content)
    So can it happen? And in which cases?

    can you telll me those few cases for this method ?
    I am interested in cases when io operations on local non empty file may lead to blocking call so that this method will return false

  • How to make find methods return a subset of the result?

    Take the multipage apps for instance,
    it is a common idea to return only a subset(No. 10~No. 30) of the full-list especially when there are millions item in the full-list.
    Please help me:)

    Maybe you're looking for something like a "Value List Handler"
    http://developer.java.sun.com/developer/restricted/patterns/ValueListHandler.html

  • How to make Vista partition on the HDD as first one with Recovery CD

    Hello,
    i want to format and recover the information to my "Vista" (C://) partition, which is the first. But when i choose the option "Format and recover to an existing first partition on your hard disk(without RE)" the computer began to recover to "Partition Type: windows NT NTFS (ID: 07)" which size is only 1.50 GB.
    In the middle of the process it shows "not enough space on a disk"
    Question: how to make "vista" partition the first one? What is "the first partition" in the second option of formating and recovering the system?
    Thank You for Your answers

    Hi
    You can obtain from your friends (I am sure someone has it) Microsoft WXP installations CD and install OS on C partition. On Toshiba download page you will find chipset and all necessary drivers to make WXP running properly. When finished connect external HDD or USB memory stick and copy all your data there. you can also install Nero demo version and create data CD or DVD. It is lot of work but if you have time you can do this without any problems.
    Other way connect your HDD as external one to other PC and copy all your important data. Sorry but I do not see other solution.

  • Regex and matcher only returns the first match

    Hi all.
    Im trying to rewrite some code and im using a regular expression to grab data out of a css formatted file, but im getting a bit confused. My matcher is only finding the first occurance of my pattern, how do i get it to find all occurances of my pattern?
    here is a sample css file
    .header
    font-family:arial, verdana;
    font-weight:bold;
    color:#ff00ff;
    background-image:url(background.jpg);
    .mainBody
    font-weight: bold;
    color: Red;
    padding 0px;
    }and here is my matcher code
    tstr = tstr.replaceAll("\\\\","/");
    tstr = tstr.replaceAll("\\n","");
    tstr = tstr.replaceAll("\\r","");
    Pattern styleFind=Pattern.compile("^\\.?[\\w\\s\\W]+?\\{.*?\\}",Pattern.DOTALL | Pattern.MULTILINE);
    Matcher styleMatch=styleFind.matcher(tstr);
    while(styleMatch.find())
    System.out.println("[A]"+styleMatch.group());
    }     i thought that if i did while(macther.find) then it would keep looping through finding all of the matches, but it is only finding the first match.
    any ideas what im doing wrong?

    tstr = tstr.replaceAll("\\\\","/");
    tstr = tstr.replaceAll("\\n","");
    tstr = tstr.replaceAll("\\r","");
    Pattern
    styleFind=Pattern.compile("^\\.?[\\w\\s\\W]+?\\{.*?\\}", Pattern.DOTALL | Pattern.MULTILINE);
    Matcher styleMatch=styleFind.matcher(tstr); You do MULTILINE despite the fact that you delete all end of line characters first. The '^' matches only at the very beginning of the input.
    Apart from that I would prefer "[^\\}]" anytime ofer ".*?\\}", because what you want is a shortest match which often turns out not to be the same as a non-greedy match.
    Harald.
    Java Text Crunching: http://www.ebi.ac.uk/Rebholz-srv/whatizit/software

  • How to make timecode track in transcoded file match original

    Using Compressor 4.1.3, when I make an H264 QT from a DNX36 QT, the timecode track does not replicate properly.  The first frame of timecode repeats for a frame which makes every frame after that read as one frame earlier than it is in the original file.
    For example, the first frame of the original file is 01:00:00:00.  In the H264, the 1st and 2nd frames are 01:00:00:00, and the 3rd frame is 01:00:00:01.  The 3rd frame should be 01:00:00:02.
    The DNX36 is a QT Reference movie exported from Avid MC 7.0.4.1.  I am reading the timecode on the QuickTimes using QuickTime Player 7.6.6. This works correctly with Mac OS 10.7.5 and Compressor 3.5.3.
    The system I'm having the trouble on is Mac OS 10.9.4, Compressor 4.1.3
    Any ideas on how to make the timecode track of the transcoded file match the original?
    Thanks.

    I'm not sure what you are getting at. Is a string child the contents of a node treated as text?
    If you are trying to match a child node regardless of case I doubt this is possible as the XML standard says an XML document is case sensitive so if your parser ignored case it would not be XML complient.
    Hope this helps.

  • How can i make a soft return with pages shift enter does not work!

    how can i make a soft return with pages shift plus enter does not work!!

    On full keyboards with a numeric keypad, the key above the right shift is "return" & the one on the numeric section is "enter." On a Mac (or Apple IIgs ) they do have separate functions. On the "mini" keyboards, both names are on the same key, but "enter" is written in smaller letters. I'll have to check to see how that works on another Mac later today.

  • How to make Sales group and office field mandatory in VA01 first screen

    hi gurus,
    can anybody tell me how to make Sales group and sales office mandatory field on VA01 tcode first screen. i have requirement to make it compulsary on the first screen otherwise they wont be able to goto next screen.
    will reward points for sure
    thanks
    mandy

    Hi! Mandy,
    Try using t.code SHD0, choose your transaction variant here, further choose your screen variant.
    Next select your screen variant and in the Menu bar select Variant> change with processing>Make repairs in foreign namespaces only if they are urgent> Continue(Enter)>again 'enter'>Object can only be created in SAP package>continue(enter)> Exit and save >This variant contains other screens, adopt these as well?>enter>enter> scroll down to the entry required by you make the necessary changes(Output only, invisible or required) and save.
    The system will prompt to assign a package and request enter the necessary values.
    Provide your feedback.
    Regards,
    PATHIK

  • How to make Address Book obey Preferences? I run MacBook Pro 4.1 laptop,  Mac OS X 10.6.8  Address Book 5.0.3 (883) Preferences set at ... General First name following Last name   Sort for Last name Address Format Canada Font size Large Phone format set a

    How to make Address Book obey Preferences?
    I run MacBook Pro 4.1 laptop,  Mac OS X 10.6.8
    Address Book 5.0.3 (883) 
    Preferences set at ...
    General
    First name following Last name 
    Sort for Last name
    Address Format Canada
    Font size Large
    Phone format set at
    +1.123.456.7890
    When application quits - it's all forgotten and it self-resets to
    unwanted configuration.

    Whenever you remove system modifications, they must be removed completely, and the only way to do that is to use the uninstallation tool, if any, provided by the third-party developers, or to follow their instructions. If the software has been incompletely removed, you may have to re-download or even reinstall it in order to finish the job.
    Here are some general guidelines. Suppose you want to remove something called “BrickYourMac.” First, consult the product's Help menu, if there is one, for instructions. Finding none there, look on the developer's website, say www.brickyourmac.com. (That may not be the actual name of the site; if necessary, search the Web for the product name.) If you don’t find anything on the website or in your search, email the developer. While you're waiting for a response, download BrickYourMac.dmg and open it. There may be an application in there such as “Uninstall BrickYourMac.” If not, open “BrickYourMac.pkg” and look for an Uninstall button.
    If you can’t remove software in any other way, you’ll have to erase your boot volume and perform a clean reinstallation of OS X. Never install any third-party software unless you're sure you know how to uninstall it; otherwise you may create problems that are very hard to solve.
    Trying to remove complex system modifications by hunting for files by name often will not work and may make the problem worse. The same goes for "utilities" that purport to remove software.

Maybe you are looking for