Finding a pattern within a String

How can I find a pattern within a string using Java? does Java has the ability to do this or do I have to write a function?

The String API documentation shows how to do it.

Similar Messages

  • Finding a word within a string

    Hey everyone,
    Just having a little trouble with something.
    I'm trying to find a word -- that is, not a substring, an actual word as defined by the english language -- within a string.
    For example I don't want "hell" to be found in "hello".. only "hello" to be found.
    Currently i've got two strings, one is the sentance (String input), and one is the word to be found in the sentance (String word). I need the program to find the WORD, and then go back and search for the word again and again and again until it reaches the end of the string.
    This is what I've got thus far:
              for(i = 0; i < input.length(); i++)
                   // This statement checks the string "input" for the string "word" starting at offset 0 (as this is what the variable was first defined as)
                   if(input.indexOf(word, offset) >= 0)
                        // If it finds the word at all, this line increases the offset ahead of this word so it doesn't simply find the same word again
                        offset = offset + (input.indexOf(word)) + (word.length());
                        times++;
              }At the moment this searches for the sub-string, not the WORD which is what I would like it to do.
    What's the easiest way of going about this? I've been fiddling around trying to add extra sections to the if statement, for example
    if((input.indexOf(word, offset) >= 0) && (input.charAt(offset +1) == 32))(32 as in the ASCII character for a space, which would do what I wanted it to do)
    But I eventually get errors because at some stage or another the charAt is going to be higher than the actual length of the String. Plus, this only looks if there's a space next to the word - a word can be valid if it has a ! next to it for example, or a comma...
    Thanks for any help :)
    viddy

    I think there's a word boundary marker in regex. So it'd be "\\w+hello\\w+" or whatever the marker is, to be used with a Pattern instance.

  • OBIEE - Find position of the last occurrence of a charcter within a string.

    Hi,
    I have a requirement in 11.1.1.6.9 to be locate the position of the last occurrence of a character within a string.
    i.e. Given the following, I would want to locate the last "/":
    This/is/an/exampleI would like to return a value of 11. Now, there could be any number of "/" so I can't always locate the nth one - it must be the last one.
    Anyone any ideas?
    Thanks,
    John

    Your requirement is not complete. just in case you want to extract the last part 'example' just use substring and replace to trim up to required part.
    You may have to go for the same for multiple times.
    ETL is the best to handle this than BI.
    BTW: Check this How to use locate function if multiple occurences of same character
    Edited by: Srini VEERAVALLI on May 10, 2013 10:25 AM
    Good that given link is helped you to solve it ;)
    Edited by: Srini VEERAVALLI on May 13, 2013 7:47 AM

  • How to search for a particular pattern in a string

    Hi,

    Hi ,
    How to search for a particular pattern in a string?
    I heard about java.util.regex; and used it in my jsp program.
    Program I used:
    <% page import="java.util.regex"%>
    <% boolean b=Pattern.matches("hello world","hello");
    out.println(b);%>
    I run this program using netbeans and am getting the following error message.
    "Cannot find the symbol : class regex"
    "Cannot find the symbol : variable Pattern "
    How to correct the error?

  • [regex help]Find EXACT characters in a String.

    Ok, i got this so far ...
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class Testing2 {
        public static void main(String[] args) {
            Pattern p = Pattern.compile("[wati]");
            String text = "water";
            Matcher m = p.matcher(text);
            if (m.find()) {
                System.out.print("Found !");
    }With that code i got a match, but i ONLY want to find a match if the String matches the EXACTS characters in the Pattern ...
    in this case i got, 'w' 'a' 't' 'i', 'w' 'a' 't', are in water, but 'i' NOT, so i don't want to have a match !
    i don't know how to acomplish this :(
    hope you can help me, thanks in advance :D

    Username7260 wrote:
    Ok, i got this so far ...
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class Testing2 {
    public static void main(String[] args) {
    Pattern p = Pattern.compile("[wati]");
    String text = "water";
    Matcher m = p.matcher(text);
    if (m.find()) {
    System.out.print("Found !");
    }With that code i got a match, but i ONLY want to find a match if the String matches the EXACTS characters in the Pattern ...
    in this case i got, 'w' 'a' 't' 'i', 'w' 'a' 't', are in water, but 'i' NOT, so i don't want to have a match !
    i don't know how to acomplish this :(AFAIK there's no syntax in regular expressions to accomplish this. Try turning your string into a character array, sorting it, and then do a simple comparison.

  • Pattern matching in String

    Hi,
    I want to do pattern matching using String. Here is my requirement.
    String file_name = (String)hash.get("DOCNAME"));
    file_name = file_name.replace("'","285745@");
    So, whereever I have '(apostrophe) I will replace it with pattern "285745@" and then at another jsp where I get this request parameter I do reverse as follows:
    String docname = (String)request.getParameter("doc_name").replace("285745@","'");
    Now I know replace function is not going to do this. It is just a indicative, for you to know what I want to achieve. which other java function / method i can implement to get the desired result.
    thanks,
    pp

    String file_name = (String)hash.get("DOCNAME"));
    file_name = file_name.replace("'","285745@");The problem here is that String.replace() operates only on char arguments, you cannot replace entire substrings with it.
    The String.replaceAll() method, on the other hand, operates on regular expressions. In many common cases (those in which the substring you want to find contains no characters with special meaning to the regular expression processor) you can use it exactly as you would String.replace() except that it operates on substrings.
    But regular expressions are much more powerful than that. The javadoc for the "Pattern" class has some information on how to use them. There is also a tutorial at http://java.sun.com/docs/books/tutorial/extra/regex/intro.html which you might find helpful.
    In the 1.4 edition of Java there is no longer any need to screw around with while loops and StringBuffers. Nearly any text processing operation can be done with regular expressions.

  • Pattern matching in Strings

    Hi,
    I need some help using pattern matching in strings .. this is what i need to do ..
    if given a string of this format
    String tempNotes="07/07/05 3:42 PM - 65. Java forum test 07/01/05 5:11 PM - 62. Trying regualt Expressions";I need to extract the number(s) after the time .. in the above case would be 65,62 .
    The string might have more than one line of the above format .. can some one help me with this .
    I tried using regular expressions .. I am pretty new to Regex's tried this
    String regex="\\d(2)/\\d(2)/\\d(2)\\s\\d+:\\d(2)\\sP|AM\\s-";
    Pattern p= Pattern.compile(regex);
    Matcher m1 = p.matcher(tempNotes);
    if(m1.find()){
    System.out.println("Num = "+tempNotes.substring(m1.end()+1,m1.end()+3));
    } I am totally lost .. can someone help me with this please. I need to extract all the numbers after the time .
    Thanks in advance.

    I see two major problems with that regex. First, you're using parentheses where you should be using braces - "\\d{2}", not "\\d(2)". Second, you need to need to limit the scope of the alternation: "(?:P|A)M", or better, use a character class instead: "[PA]M". As it is, the vbar is splitting the whole regex into two alternatives. Also, you can use a capturing group to extract the number.
      String regex="\\d{2}/\\d{2}/\\d{2}\\s\\d+:\\d{2}\\s[AP]M\\s-\\s+(\\d+)";
      Pattern p= Pattern.compile(regex);
      Matcher m1 = p.matcher(tempNotes);
      while (m1.find()) {
        System.out.println("Num = " + m1.group(1));
      }

  • To find a word in a string.

    Please, is there a way to find a word in a string?
    For exemple:
    The string contains... "Hello World Java Sun"
    I need to find the word "Java", and I'd like to do not compair char by char... I'd like to do it faster than one by one...
    Is there a way? How should I do? I was thinking to use something like substring... but even it... I need to compair char by char... (or I didn't?)
    Thanks a lot

    go to search engine and learn the String class it will help u in the future.
         indexOf
    public int indexOf(String str)
        Returns the index within this string of the first occurrence of the specified substring. The integer returned is the smallest value k such that:
             this.startsWith(str, k)
        is true.
        Parameters:
            str - any string.
        Returns:
            if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned

  • How to find out if a long String has a "subString" twice or more.

    I need to find out if a long String has the same number twice or more.
    I need to look matches for numbers running from 000, 001....999 and if a number is found twice or more, return that number and lines there were found.
    example String:
    -;000 ; 1 ; 2006-12-11 ; -; job;
    x;001 ; 2 ; 2006-12-11 ; 2006-12-12; do this
    -;002 ; 3 ; 2006-12-11 ; -; work
    -;003 ; 0 ; 2006-12-11 ; -; some
    -;004 ; 2 ; 2006-12-11 ; -; thing
    x;005 ; 1 ; 2006-12-11 ; 2006-12-11; reads
    -;003 ; 0 ; 2006-12-11 ; -; here
    Should return from example String:
    003 at lines 4 and 7
    Any ideas?

    So there are newlines in the String?
    You could use a StringTokenizer to break the String into lines, then searching on each line if it contains any of the search strings. (You need to clarify if a line can contain more than one search string).
    Probably you should use a Map<String, Integer> to record the searchcounts.
    Or an int[] Array if you are really sure that the Strings you search for really are numbers.
    Another option is to use:
    LineNumberReader lnr = new LineNumberReader(new StringReader(searchString));This will save you from explicitly having to take care for the line number.
    In any case your example looks like the individual lines are semicolon separated fields and the numbers you search for always are in column two.
    So after breaking up the original String in lines, you could use another StringTokenizer to break up the line in fields.

  • Finding the key according to string length in java.util.Properties

    Finding the key according to string length in java.util.Properties.
    I know only String length only.

    i need to retrieve the values from the java.util.properties.
    we know that we need to give the key value in order to retrieve the datas.
    but my problem is i will give the length of the key instead of giving the key value but i need to retrieve the datas according to the length of the key.

  • Process Message failed: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.

    Hi
    I am trying to process an X12 message and I am getting following error.
    Method : ProcessMessage
    Message : Process Message failed: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
    Parameter name: length
       at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy)
       at Q.Inbound.X12Preprocessor.getTranTypeFromFuncCode()
       at Q.Inbound.X12Preprocessor.setProcessType()
       at Q.Inbound.X12Preprocessor.getFuncGroupHeader(StreamReader sr)
       at Q.Inbound.X12Preprocessor.ProcessMessage(X12Definition& docInfo)
    Please help.
    Thanks

    Might try them over here.
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=csharpgeneral%2Cvbgeneral%2Cvcgeneral&filter=alltypes&sort=lastpostdesc
    Regards, Dave Patrick ....
    Microsoft Certified Professional
    Microsoft MVP [Windows]
    Disclaimer: This posting is provided "AS IS" with no warranties or guarantees , and confers no rights.

  • [JS - CS3]  Can't REPLACE A with B within a string? Help Please...

    Hello Experts,
    First off - I'm a newbee to all this JS and especially with CS3.
    I have a string: '
    b myDocumentName
    which can have it's value as: '
    b 00000en_ Generator WX/WY
    Problem is, backshlashes ( / )are a bad thing for me...
    b Question:
    How can I do a 'replace' operation to replace the '/' from the string with a '_'?
    I have at the moment:
    > var myDocSaveName = oneResult[3]+oneResult[4]+oneResult[5];
    > myDocSaveName.replace(what "/", with "");
    > myDoc.save ("C:/DATA/"+myDocSaveName, undefined, undefined, true)
    I get an error Nr. 25... Offending text:"/"
    What am I doing wrong?

    'what' and 'with' are the names of those arguments. They should not be included in the statement:
    myDocSaveName.replace("/", "");
    But that still won't work because replace doesn't operate on a string in situ, it returns the modified string. So:
    myDocSaveName = myDocSaveName.replace("/", "");
    This too has its limitations. It'll change only the first instance of "/", not all of them. To change all of them, you need to restate the 'what' as a RegExp:
    myDocSaveName = myDocSaveName.replace(/\//g, "_");
    A RegExp literal is delimited by the "/" character, so to have it, alone, as the character to be sought you must use the backslash to escape the character. Then, to indicate you want the replace to happen globally within the string, you add the 'g' after the RegExp.
    Dave

  • Find/Change problems within a nested style?

    I have a problem with Find/Change (in both CS4 and CS5) not recognizing text within its “find” parameters when text that fits those parameters is part of a nested style. I want to find any instance of italic in the text, regardless of what paragraph or character style it is, but F/C only intermittently finds italics, both within and without that text existing in a nested style. Has anyone come across this issue?
    There is NOTHING different about the text that is recognized by F/C–or not recognized–that shows up in any of the panels or palettes. There are no font conflicts. I’ve replaced prefs and saved data files. If I go into the character palette and change the italic portion of the nested style to “italic” character style (it shows up in character palette as [none], even though it has a nested style), then F/C finds it for sure; but if I don’t do that, then F/C will sometimes find it, and sometimes not, and sometimes in one instance and not in another! There is no hidden formatting that shows up in story editor. I remade another nested para style with the same formatting but with varying results! Help… I’ve tried everything.

    I have a problem with Find/Change (in both CS4 and CS5) not recognizing text within its “find” parameters when text that fits those parameters is part of a nested style. I want to find any instance of italic in the text, regardless of what paragraph or character style it is, but F/C only intermittently finds italics, both within and without that text existing in a nested style. Has anyone come across this issue?
    There is NOTHING different about the text that is recognized by F/C–or not recognized–that shows up in any of the panels or palettes. There are no font conflicts. I’ve replaced prefs and saved data files. If I go into the character palette and change the italic portion of the nested style to “italic” character style (it shows up in character palette as [none], even though it has a nested style), then F/C finds it for sure; but if I don’t do that, then F/C will sometimes find it, and sometimes not, and sometimes in one instance and not in another! There is no hidden formatting that shows up in story editor. I remade another nested para style with the same formatting but with varying results! Help… I’ve tried everything.

  • How to get a set of character within a string?

    Hi,
    I need to cut a set of character within a string. I have tried everthing but I need help.
    Example.
    Database Version 11.2.0.3
    create table tst_string (message varchar2(600));
    insert into tst_string values ('ANR0166I Inventory file expiration finished processing for node OSOGBO, filespace OSOGBO\SystemState, copygroup BACKUP and object type GROUP BASE with processing statistics: examined 43, deleted 43, retrying 0, and failed 0. (SESSION: 1506, PROCESS: 2)');
    insert into  tst_string values ('ANE4175I Starting Full VM restore of VMware Virtual Machine ''mfujiwara'' target node name=''VC1_DC1'', data mover node name=''VC1_DC1_DM3''  (SESSION: 3780)');
    commit;
    select * from tst_string;
    MESSAGE
    ANR0166I Inventory file expiration finished processing for node OSOGBO, filespace OSOGBO\SystemState, copygroup BACKUP and object type GROUP BASE with processing statistics: examined 43, deleted 43, retrying 0, and failed 0. (SESSION: 1506, PROCESS: 2)
    ANE4175I Starting Full VM restore of VMware Virtual Machine 'mfujiwara' target node name='VC1_DC1', data mover node name='VC1_DC1_DM3'  (SESSION: 3780)
    ## I want get
    # From first line following values:
    node OSOGBO
    filespace OSOGBO\SystemState
    examined 43
    deleted 43
    retrying 0
    failed 0
    # From second line
    mfujiwara
    VC1_DC1
    VC1_DC1_DM3Any help can be useful...
    Thanks in advance.

    Hi Frank,
    It looks like message can be seen as delimited lsit of sub-messages, where a number of different characters (perhaps ',' amd ':') may serve as delimiters. Each sub-message may or consist (entirely or in part) of something you want to display.Yes. In my first case where is "ANR0166I" I want get the characteres before "," (e.g "OSOGBO," I want get "OSOGBO") excluding "(SESSION: 1506, PROCESS: 2)"
    Would a user-define PL/SQL function be okay for you?Yes.. no problem.
    I'm not good with shell script, but will try show what I want using SHELL commands:
    See this example:
    ### I create a file named "tst_string"
    $ vi tst_string
    ANR0166I Inventory file expiration finished processing for node OSOGBO, filespace OSOGBO\SystemState\NULL\System State\SystemState, copygroup BACKUP and object type GROUP BASE with processing statistics: examined 43, deleted 43, retrying 0, and failed 0. (SESSION: 1506, PROCESS: 2)
    ## So I used a function sed to get my desired values. The command bellow is poor, but My point is the result.
    $ cat tst_string | sed 's/ANR0166I.*node //g' | sed 's/, filespace//g' | sed 's/, copygroup BACKUP and object type GROUP BASE with processing statistics: //g' | sed 's/. (SESSION.*//g' | sed 's/, deleted//g' | sed 's/, retrying//g' | sed 's/, and failed//g'
    OSOGBO OSOGBO\SystemState\NULL\System State\SystemState 43 43 0 0The result was:
    NODE     FILESPACE                              Examined     Deleted     Retrying        Failed      
    OSOGBO      OSOGBO\SystemState\NULL\System State\SystemState     43           43      0           0I will go check the links wich you mentioned.
    Thanks

  • Using CTRL + F not working to find any text within the query result

    Hi friends,
    I am trying to use find option to find any text within the result section of a query but when I do CTRL+F  the find window appears and I can input the text that I wanted. But when I press Enter it is not giving me any result though the entered text
    is in the query result. I am using Sql Server 2012 Management studio. Any Body please help me. There is a job that I have to search certain things after running a script and now I am doing copy paste to excel and doing searching from there. 

    Prashant,
    Looks like you are trying to do in SSMS, and it is because the result set is in Grid view , if you want to use CTL + F then your result should be in Text format, try to do using CTL + T ( To get result in Text) and then use CTL + F to find any
    text.
    Thanks
    Manish
    Please click Mark as Answer if my post solved your problem and click
    Vote as Helpful if this post was useful.

Maybe you are looking for

  • How To run jdk1.4.1 application in jdk1.1.6?

    Hi, we have developed product into jdk1.1.6 and it is used by many of our clients, now we r developing patches to the product using java2. How to run these packges using older version of java. we tried using runtime, but it is not working so plz if t

  • Two ADC 17" mac displays w/Mac Pro?

    I have a pair of the older 17" Mac displays with ADC connectors. I used them with my old MDD G4, which came with a video card that had DVI and ADC connectors. So, I obviously had to buy an ADC/DVI converter so I could use the DVI port that the comput

  • Quotation report

    I am building a report in quotes and it's almost done. A couple of things are keeping from completion. 1) If a quote has multiple line items and each material has numerous quantities, how do I determine the qty of a given material that has been compl

  • Exception when invoking create method on entity ejb's home object

    I have a simple entity bean. I am able to get the reference to the entity's home object. But when I run create method on entity's home interface, I get the following exception. The create method takes no arguments as the primary key is Auto-Increment

  • SOAP:1.023 SRT: Processing error in Internet Communication Framework

    Hi, We are developing consumer proxies on ECC enhancement Package 4. Could you please advice us on the mandatory Technical Configuration that is required in order to consume Web Services from external (non-SAP systems) Providers? We are trying to tes