Sub string from a word to another word

I want to find word "cat" from the sentence: My cat is missing.
Please provide a generic solution which works for ant set of statements for finding a word.

Since "cat" can be found inside of other words it is better to use Regex to extract hole words like in the code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication21
class Program
static void Main(string[] args)
string input = "My cat is missing";
string pattern = @"^(\w+\s?)+$";
Regex expr = new Regex(pattern);
Match match = expr.Match(input);
Group group = match.Groups[1];
foreach (Capture capture in group.Captures)
Console.WriteLine("Word : {0}", capture.ToString());
jdweng
I'd like to suggest a couple of changes to build on Joel Engineer's answer.
Firstly, that's a rather restrictive pattern.  The period at the end of the sentence will confound it (which I notice was removed from the example), and so would a word like "isn't".  I'd use \b to make this pattern:
\bcat\b
\b matches a word boundary, and is specifically designed for performing whole-word matching like this.
Also, a case-insensitive matching option would be good here.
Then you can get the index of the match using Regex.Matches, which seems more useful than just knowing whether "cat" is in there somewhere or not, and seems more in the spirit of actually
finding the match.
static void Main( string[] args )
string input = @"My cat is missing.";
string pattern = @"\bcat\b";
MatchCollection matches = Regex.Matches( input, pattern, RegexOptions.IgnoreCase );
if( matches.Count > 0 ) {
// found
Console.WriteLine( "Found at index {0}", matches[0].Index );
} else {
Console.WriteLine( "Not found" );

Similar Messages

  • How to put a string from one Frame to another Frame?

    Dear all,
    How can I put a String from one Frame to another Frame?
    When the application started, the Frame 'WindowX' will be displayed. After you press the 'openButton', a whole new Frame (inputFrame) will be shown. In this Frame )(inputFrame) you can write a String in a TextField. After pressing the okButton, this String will be sent to the first Frame 'WindowX'.
    But does anyone know how to realize the sending part?
    I've tested this code on Win98 SE and JDK1.2.2.
    Hope someone can help me. Thanks in advance.
    import java.awt.*;
    import java.awt.event.*;
    public class WindowX extends Frame implements ActionListener, WindowListener
         private Button openButton;
         private TextField resultField;
         public static void main(String [] args)
              WindowX wx = new WindowX();
              wx.setSize(300,100);
              wx.setVisible(true);
         public WindowX()
              setLayout(new FlowLayout());
              openButton=new Button("open");
              add(openButton);
              openButton.addActionListener(this);
              resultField=new TextField(10);
              add(resultField);
              resultField.addActionListener(this);
              addWindowListener(this);     
         public void actionPerformed(ActionEvent evt)
              if (evt.getSource()==openButton)
                   inputFrame ip=new inputFrame();
                   ip.setSize(200,80);
                   ip.show();
         public void place(String theString) //this doesn't work
              resultField.setText(theString);
         public void windowClosing(WindowEvent event)
              System.exit(0);
         public void windowIconi......
    class inputFrame extends Frame implements ActionListener,WindowListener
         String theString = "";
         Button okButton;
         TextField inputField;
         WindowX myWX=new WindowX();   //??
         public inputFrame()
              setLayout(new FlowLayout());
              inputField=new TextField(10);
              add(inputField);
              inputField.addActionListener(this);
              okButton=new Button("OK");
              add(okButton);
              okButton.addActionListener(this);     
              addWindowListener(this);     
         public static void main(String[] args)
              Frame f = new Frame();
              f.show();
         public void actionPerformed(ActionEvent evt)
              if (evt.getSource()==okButton)
                   theString=inputField.getText();
                   myWX.place(theString);   //??
                   dispose();
        public void windowClosing(WindowEvent e) {
        dispose();
        public void windowIconi......
    }

    Thanks for your reply!
    But I got an other problem:
    I can't refer to the object (wx) made from the main Frame 'WindowX', because it's initialized in 'public static void main(String [] args)'...
    Hope you can help me again... Thanks!
    import java.awt.*;
    import java.awt.event.*;
    public class WindowX extends Frame implements ActionListener, WindowListener
         private Button openButton;
         private TextField resultField;
         public static void main(String [] args)
              WindowX wx = new WindowX();   //!!
              wx.setSize(300,100);
              wx.setVisible(true);
         public WindowX()
              setLayout(new FlowLayout());
              openButton=new Button("open");
              add(openButton);
              openButton.addActionListener(this);
              resultField=new TextField(10);
              add(resultField);
              resultField.addActionListener(this);
              addWindowListener(this);     
         public void actionPerformed(ActionEvent evt)
              if (evt.getSource()==openButton)
                   inputFrame ip=new inputFrame(wx);
                   ip.setSize(200,80);
                   ip.show();
         public void place(String theString)
              resultField.setText(theString);
         public void windowClosing(WindowEvent event)
              System.exit(0);
         public void windowIconi....
    class inputFrame extends Frame implements ActionListener,WindowListener
         String theString = "";
         Button okButton;
         TextField inputField;
         WindowX parent;
         public inputFrame(WindowX parent)
              setLayout(new FlowLayout());
              this.parent=parent;
              inputField=new TextField(10);
              add(inputField);
              inputField.addActionListener(this);
              okButton=new Button("OK");
              add(okButton);
              okButton.addActionListener(this);     
              addWindowListener(this);     
         public static void main(String[] args)
              Frame f = new Frame();
              f.show();
         public void actionPerformed(ActionEvent evt)
              if (evt.getSource()==okButton)
                   theString=inputField.getText();
                   parent.place(theString);
                   dispose();
        public void windowClosing(WindowEvent e) {
        dispose();
        public void windowIconi..........
    }          

  • When I click from one screen to another, Word becomes active.

    Let's say I'm using Mail on my primary display. If I then click on a Safari window on my secondary display, Microsoft Word becomes active. (Its windows come to the front and the menu bar becomes the Word menu bar). I then have to click on the Safari window again to actually use it. Then let's say I click on a Finder window back on my primary display. Again, Word becomes active. Obviously this is a bug. Has anyone else seen it? Does anyone have a solution? Thanks.

    I'm suddenly having the same problem. Find a cure yet?

  • Returning a string from one class to another

    I have a file from where i creating an object of another class and calling the fuctionsl
    This is how i am doing
    public login()
    String input =new String (passwordField.getPassword());
         input= input.trim();
    tempuser= userField.getText();
              db2sqln patientsqln =new db2sqln(); //creating an object
              patientsqln.connectdb2();// calling a connect to database function
              patientsqln.dbselect(tempuser);// passing the login informaiont
    in patientsqln i am getting the password from the database and want to pass it back to login class so that i can compare the entered password and the database password
    here is i am using my patientsqln.dbselect()
    //public void dbselect(String userinput)
              try
              Statement stmt = con.createStatement();
              String select = "Select patientpass from patient where PATIENTUSER="+"'"+userinput+"'";
              ResultSet rs = stmt.executeQuery(select);
              while (rs.next())
              name=rs.getString("PATIENTPASS");
              name = name.trim();
              System.out.println(name+"from db2sqln");
              rs.close();
    My question is that everything else works fine, but i donot get any password back in login() class it returns null value. looks like i am not returing the string back. how should i do that
    I am comparing like this
    if(input.equals("name"))
    System.out.println("Correct password");
    else{
    System.out.println("Incorrect password");
    //

    I have a file from where i creating an object of another class and calling the fuctionsl
    This is how i am doing
    public login()
    String input =new String (passwordField.getPassword());
    input= input.trim();
    tempuser= userField.getText();
    db2sqln patientsqln =new db2sqln(); //creating an object
    patientsqln.connectdb2();// calling a connect to database function
    patientsqln.dbselect(tempuser);// passing the login informaiont
    in patientsqln i am getting the password from the database and want to pass it back to login class so that i can compare the entered password and the database password
    here is i am using my patientsqln.dbselect()
    //public void dbselect(String userinput)
    try
    Statement stmt = con.createStatement();
    String select = "Select patientpass from patient where PATIENTUSER="+"'"+userinput+"'";
    ResultSet rs = stmt.executeQuery(select);
    while (rs.next())
    name=rs.getString("PATIENTPASS");
    name = name.trim();
    System.out.println(name+"from db2sqln");
    rs.close();
    My question is that everything else works fine, but i donot get any password back in login() class it returns null value. looks like i am not returing the string back. how should i do that
    I am comparing like this
    if(input.equals("name"))
    System.out.println("Correct password");
    else{
    System.out.println("Incorrect password");
    //

  • How to pass string from a class to another on button click

    Hai forum i'm developing an application in which i have frame1(seperate class without main) where i get a excel files and get the tablenames of it(sheets).
    There i choose a sheet from availabe sheets and i have to pass it frame2 on clicking a button on frame1.
    The sheet name is chosen from a JComboBox in frame1:(code)
    sheetcombo.addActionListener(new java.awt.event.ActionListener()     
                        public void actionPerformed(java.awt.event.ActionEvent e)
                                  JComboBox cb = (JComboBox)e.getSource();
                                  String sheetname = (String)cb.getSelectedItem();
    I dont get how to pass this String sheetname to frame2 where i call the constructor of frame1 initialize it. Help me out. Thanks in advance...

    1 write a set method in frame 2 class
    2 create a instance of frame 2 class in frame 1
    3 in actionaPerformed method write code as follows
    frame2obj.set(sheetname)
    this should work :-)

  • Pasing a string from one frame to another can anyone help

    HI
    i have a textboxA in frame1 with a string eg.someones name. when sone one clicks on button A, Frame be will open up with the contents of texyboxA being placed in Textboxb in Frame 2.
    can anyone show how i can do this. thanks#
    it would get be out of a very big hole

    Here is a simple example for the same page. Now all you have to do is change the action to send it to the other page.
    package sendforminfo;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    public class Applet1 extends Applet {
    boolean isStandalone = false;
    TextField textField1 = new TextField();
    Button button1 = new Button();
    Label label1 = new Label();
    //Get a parameter value
    public String getParameter(String key, String def) {
    return isStandalone ? System.getProperty(key, def) :
    (getParameter(key) != null ? getParameter(key) : def);
    //Construct the applet
    public Applet1() {
    //Initialize the applet
    public void init() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    //Component initialization
    private void jbInit() throws Exception {
    textField1.setText("Send this data");
    textField1.setBounds(new Rectangle(32, 33, 161, 27));
    this.setLayout(null);
    button1.setLabel("push me");
    button1.setBounds(new Rectangle(259, 36, 86, 24));
    button1.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    button1_mouseClicked(e);
    label1.setBounds(new Rectangle(129, 105, 154, 31));
    this.add(label1, null);
    this.add(textField1, null);
    this.add(button1, null);
    //Get Applet information
    public String getAppletInfo() {
    return "Applet Information";
    //Get parameter info
    public String[][] getParameterInfo() {
    return null;
    void button1_mouseClicked(MouseEvent e) {
    label1.setText(textField1.getText());
    <html>
    <head>
    <title>
    HTML Test Page
    </title>
    </head>
    <body>
    <applet
    codebase = "."
    code = "sendforminfo.Applet1.class"
    name = "TestApplet"
    width = "400"
    height = "300"
    hspace = "0"
    vspace = "0"
    align = "middle"
    >
    </applet>
    </body>
    </html>
    The crux of the methos is the statement
    void button1_mouseClicked(MouseEvent e) {
    label1.setText(textField1.getText());
    Which sends the information. Hope this helps. Tomorrow if I have time I'll write up and example with Frames. Right now I'm in my own JAVA hell.

  • How to extract sub string value from a string?

    Hi,
    I need to know how can i extract sub strings from a main
    string, something like this:
    main variable-------->"2087-5E2SE-19-JG7BC"
    i want to split it into like this:
    sub_main_1 variable---------> "2087"
    sub_main_2 variable---------> "5E2SE"
    sub_main_2 variable---------> "19"
    sub_main_2 variable---------> "JG7BC"
    I did the same in flash by using Split and arrays, like this:
    var my_str:String = "2087-5E2SE-19-JG7BC";
    var my_array:Array = my_str.split("-");
    for (var i = 0; i<my_array.length; i++) {
    trace(my_array
    this.aaa1 = my_array[1];
    this.aaa2 = my_array[2];
    this.aaa3 = my_array[3];
    this.aaa4 = my_array[4];
    My question is that how can i do the same in director ?? i
    haven't find any split function in director.
    Thanks in advance,
    Amir

    You do a similar thing in Director using the itemDelimiter,
    which is a
    _player object property in MX2004. By default, it's a comma:
    put _player.itemDelimiter
    It will let you get specific items within a string.
    p = "2087-5E2SE-19-JG7BC"
    _player.itemDelimiter = "-"
    put p.item[1]
    -- "2087"
    You could use it to write yourself a little split function:
    on split(theString, theDelimiter)
    oldDelim = _player.itemDelimiter
    _player.itemDelimiter = theDelimiter
    itemList = []
    repeat with cnt = 1 to theString.item.count
    itemList.add(theString.item[cnt])
    end repeat
    return itemList
    end
    p = "2087-5E2SE-19-JG7BC"
    a = split(p, "-")
    put a
    -- ["2087", "5E2SE", "19", "JG7BC"]
    Dave -
    Adobe Community Expert
    www.blurredistinction.com
    http://www.adobe.com/communities/experts/

  • Searching Sub String

    Any idea how can I search a sub string from a String ignoring white spaces.
    Ok, I need to Search a sub string ("for update") from a given String (henceforth Source String) but the condition is it might contain any number of white spaces between these two words (in source string).
    So how can I search for "for update" in Source String ignoring any number of (but at least one) white spaces it might have in the source string.
    (One way can be searching index of "for" than checking value at index+2 for "update"...and keep trying until i search through entire length of String...but I need some optimized way to do it as I need to check this virtually infinite times in my application)

    you should "normalize" the string you are searching - that is - first scan it for white space and replace them with single spaces. Then convert it to lower case and search it for what you wish. You could use StringTokenizer -
    StringTokenizer st = new StringTokenizer( toBeSearched, " \r\n\t" );
    StringBuffer sb = new StringBuffer();
    while( st.hasMoreTokens() ) sb.append( st.nextToken() + " " );
    String toBeSearchedN = sb.toString().toUpperCase().toLowerCase();
    String toSearchForN = toSearchFor.toUpperCase().toLowerCase();
    boolean result = ( toBeSearchedN.indexOf( toSearchForN ) != -1 );

  • Moving Image from one Review to Another?

    I attempted to upload an image (open in Photoshop) to a specific review. However, I could not see the desired review in the Photoshop CS Review panel. Out of frustration - after attempting to "find" the desired review for several minutes - I uploaded the image to another review and then went online, using Safari, to Acrobat.com.
    There is no visible means of moving an image from one review to another. There is a way of dragging one review (with all sub-images) to another location. But I can't see a way of moving a sub-image from one review to another review.
    IF there is some "magic" that someone knows I would sure appreciate some education.

    This works quite well for a single image review. I've moved them from one workspace to another. The issue is when a review has multiple images and you want to take only one of them from that review and move it to another review in another workspace; I can't seem to get that to work at all.
    When I open a review and navigate to the desired image, then click in the lower left corner and select a new workspace to move the image to, it moves the entire review - not the single image - to the new workspace.
    I guess I could delete the "part" from the workspace it currently exists in and then create it as a stand alone review, but then I won't be able to imbed it into another review as I want to do.
    The source frustration here is that I can't get CS Review in CSPS5 to navigate to the desired workspace/review. I get "ALL REVIEWS" displayed but not the workspaces... Any ideas on how to display workspaces instead of reviews?

  • Returning strings from OLE2 Word object (Forms 4.5)

    Below is an example of how to return string and numeric values from OLE2 objects. In this example the OLE2 object is a MS Word document, and I want to fetch all the bookmarks in the Document into a Forms 4.5 Varchar2. To do this I first need to get the count of bookmarks.
    Getting a string property from an OLE2 object is a common OLE2 requirement but is poorly documented. This is the ONLY way it can be done, as OLE2.INVOKE_CHAR returns a single character not a string. Use OLE2.INVOKE_OBJ, then OLE2.GET_CHAR_PROPERTY which does return a string, as shown below, to return a string from an OLE object (or OLE property).
    Also note how you can only get the child object from its parent, not the grandchild (etc) object, so multiple (cascading) GET_OBJ_PROPERTY calls are required.
    /* by: Marcus Anderson (Anderson Digital) (MarcusAnderson.info) */
    /* name: Get_Bookmarks */
    /* desc: Returns a double quoted CSV string containing the document*/
    /* bookmarks. CSV string will always contain a trailing comma*/
    /* EG: "Bookmark1","Bookmark2",Bookmark3",Bookmark4", */
    /*               NB: This requires that Bookmarks cannot contain " chr */
    PROCEDURE Get_Bookmarks (pout_text OUT VARCHAR2)
    IS
    v_text           VARCHAR2(80);
    v_num                         NUMBER(3);
         v_arglist OLE2.LIST_TYPE;
         v_Application     OLE2.OBJ_TYPE;
    v_ActiveDoc      OLE2.OBJ_TYPE;
    v_Bookmarks          OLE2.OBJ_TYPE;
    v_Item                    OLE2.OBJ_TYPE;
    v_i                              NUMBER(3);
    BEGIN
              v_Application     := LDWord.MyApplication; -- Word doc opened elsewhere
                   /* Set v_num = ActiveDocument.Bookmarks.Count */
    v_ActiveDoc := OLE2.GET_OBJ_PROPERTY (v_Application, 'ActiveDocument');
    v_Bookmarks := OLE2.GET_OBJ_PROPERTY (v_ActiveDoc , 'Bookmarks');
    v_num := OLE2.GET_NUM_PROPERTY (v_Bookmarks, 'Count'); -- NB: Returns numeric property
                   /* Build the output string, pout_text. */
    FOR v_i in 1..v_num LOOP
                        /* Set v_item = ActiveDocument.Bookmarks.Item(v_i) */
    v_arglist := OLE2.CREATE_ARGLIST;
    OLE2.ADD_ARG (v_arglist, v_i);
    v_Item := OLE2.INVOKE_OBJ (v_Bookmarks, 'Item', v_arglist); -- NB: returns parent object (array element)
    OLE2.DESTROY_ARGLIST (v_arglist);
                        /* Set v_text = ActiveDocument.Bookmarks.Item(v_i).Name */
    v_text := OLE2.GET_CHAR_PROPERTY (v_Item, 'Name');                    -- NB: Returns string/varchar2 property
    pout_text := pout_text || '"' || v_text || '",' ;
    END LOOP;
    END;

    Please repost in the Forms discussion forum.
    - OTN

  • Trying to cut and paste . firefox not letting me paste a file from microsoft word to another application

    working on a new website .I want to cut and paste information from microsoft. firefox is not letting me.

    How is Firefox involved in "microsoft word to another application"?

  • Replace complete words by another string

    Hi,
    I'm searching for a possibility to replace complete words inside a string.
    For example I want to replace "quick" by "slow":
    "The <b>quick</b> brown fox is running quicker then the slow brown fox".
    The result shall be:
    "The <b>slow</b> brown fox is running quicker then the slow brown fox".
    The problem is, that the built in "Replace"-Method would also replace "quicker" by "browner".
    Furthermore, words beetween different signs (e.g. , . ; : - ! " ? ') shall also be found as complete word.
    I already searched for a FM but didn't find anything. Regular expressesions are also not possible because we are running on 6.40.
    Maybe anybody can help me with a simple FM or something else.
    Best regards,
    Stefan

    Hi Stefan,
    There is a crude way of doing this....with lots of loops..
    You can use the SPLIT statement
    SPLIT dobj AT sep INTO
          { {result1 result2 ...} | {TABLE result_tab} }
          [IN {CHARACTER|BYTE} MODE].
    and break the sentence into words using space as delimiter. Once you have all the words in a internal table, you can loop through it and compare each word with the word you want.
    This will solve the problem, but will not be performant enough.
    Regards,
    Vinodh

  • I cannot copy and paste from Word 2007 into Firefox (gmail), and I cannot copy and paste from Firefox (URLs) into a word document.

    Starting two days ago, I can no longer copy and paste between Firefox and Word 2007. I can copy within each program.

    I had similar issues starting about the same time or within the past week. However, I can copy and paste, it just takes considerably longer than it used to before. Copying something from a web page into Word could take up to 30 seconds now on my computer but it shows a busy mouse pointer while it is loading, then clicks/pops when it loads into the Word document, but then actually takes about another 5 to 10 seconds to appear in the Word document. I have no idea why it is delaying now when it did not do it before, but since it is still going into the document I am living with it for now. Are you waiting long enough to see if it appears?

  • While typing a doc in Word, the spinning wheel appeared and froze the Word document.  I had another Word doc open at the time.  I tried to force quit, but it didn't work.  I would like to save it before losing my work, but the spinning wheel blocks me.

    While creating a Word doc, the spinning wheel appeared and won't go away.  Another Word doc was open at same time.  How do I get this fixed while saving my work?

    rollrock wrote:
    How do I get this fixed while saving my work?
    Basically, you don't.
    The 'spinning wheel' is simply an indicator that an operation is taking longer than it should. It doesn't say anything about why, or even if it's an error or not. If it's in Word, it could be that the app is hung, or it could be that it is waiting for some kind of user input, or input from another app. (My bet would be on the former.) You could go into Activity Monitor, identify the process that's making it wait, kill it, cross your fingers and hope that it would generate an error that would cause Word to return control to the user (you). If you had the expertise, that is, and the moon were in right quadrant.
    Realistically, your only option is to force-quit Word. Once that is done, if AutoRecovery was on, then, with luck, you could recover much of your work. Here
    <http://kb.iu.edu/data/ahnd.html>
    you'll find a quick overview of AutoRecovery and how it works.
    If it wasn't on (it should be on by default), then you're out of luck. Chalk it up to experience, turn it on, and back to the grindstone.

  • Word For Mac Document Froze over top of another Word For Mac Document

    I have two Word for Mac documents open, one with my notes and the other being my essay.
    I needed to look up something from another word document that I accessed via an email. I downloaded the attacthed word document and opened it. It opened over top of my notes and froze. I cannot close the document that has froze so I would have to force quit Word for Mac, but that would cost me losing the document it has froze over as I am unable to save it. If this makes sense to anyone, I could really do with a hand, or be redirected where I could get some help!
    Thank you!

    All I can suggest is do a screen shot
    Shift cmd3
    or take a selection of what you want by
    shift cmd4
    save the file then force quick
    or press the power button on your machine till it quits.
    restart

Maybe you are looking for