$10 for answer: using Pattern - regular expressions and Scanner

I'm trying to read input messages using Scanner. The messages are in format: word1 word2 number. the "number" is followed by "C null terminator" i.e. '\u0000' character.
I tried this:
Scanner input;
          Pattern pat = Pattern.compile("(\\w+) (\\w+) (\\d+)\u0000");
          input.useDelimiter(pat);
          while (input.hasNext(pat)) {
The input is there and in correct format, but it hangs hasNext(pat) - as if input is not correct. What did I do wrong? Thanks in advance - thsi is urgent, I'd be glad to send you $10 for correct answer via PayPal.
Message was edited by:
MrM654

Here is a Regex and a Scanner implementation.
The price is $20 because there are 2 ways to do this.
Plus at least a $10 courtesy tip.
import java.util.Scanner;
import java.util.regex.*;
public class RegexTest{
public static void main(String[] args){
     new RegexTest();
public RegexTest(){
     String input = "word1 word1 1\u0000 word2 word2 2\u0000 word3 word3 3\u0000";
     Pattern pattern = Pattern.compile("(\\w+ \\w+ \\d+\\u0000)");
     Matcher matcher = pattern.matcher(input);
     while(matcher.find() == true){
     System.out.println("Match: " + matcher.group());
     String input = "word word 1\u0000 word2 word2 2\u0000 word3 word3 3\u0000";
     Pattern pattern = Pattern.compile("(\\w+) (\\w+) (\\d+)\\u0000\\s*");
    Scanner scanner = new Scanner(input);
     String result;
     while((result = scanner.findInLine(pattern)) != null){
     System.out.println("Match: " + result);
     System.out.println("Done.");
}Edit: Changed Pattern to end with \\s* to be insensitive to ending spaces

Similar Messages

  • Track the entered answer using the Regular expression

    Hi,
    I am building a Q&A application which does have user to answer descriptive answer for the question(Text based answer rather than objective)
    in this case how we can track the entered answer by the user is the correct one? how we can capture the entered answer and then check with the correct
    answer in the DB? Yes we need to use a regular expression , but how we know that entered one is matching with the one in the DB
    as the user can answer in lengthy or short form ? Hence please clarify how we can proceed?
    Thanks.

    797836 wrote:
    Hi,
    I am building a Q&A application which does have user to answer descriptive answer for the question(Text based answer rather than objective)
    in this case how we can track the entered answer by the user is the correct one? how we can capture the entered answer and then check with the correct
    answer in the DB? Yes we need to use a regular expression , but how we know that entered one is matching with the one in the DB
    as the user can answer in lengthy or short form ? Hence please clarify how we can proceed?
    I don't see how regular expressions help at all with this problem ! What made you think they can help?

  • "Match Regular Expression" and "Match Pattern" vi's behave differently

    Hi,
    I have a simple string matching need and by experimenting found that the "Match Regular Expression" and "Match Pattern" vi's behave somewhat differently. I'd assume that the regular expression inputs on both would behave the same. A difference I've discovered is that the "|" character (the "vertical bar" character, commonly used as an "or" operator) is recognized as such in the Match Regular Expression vi, but not in the Match Pattern vi (where it is taken literally). Furthermore, I cannot find any documentation in Help (on-line or in LabVIEW) about the "|" character usage in regular expressions. Is this documented anywhere?
    For example, suppose I want to match any of the following 4 words: "The" or "quick" or "brown" or "fox". The regular expression "The|quick|brown|fox" (without the quotes) works for the Match Regular Expression vi but not the Match Pattern vi. Below is a picture of the block diagram and the front panel results:
    The Help says that the Match Regular Expression vi performs somewhat slower than the Match Pattern vi, so I started with the latter. But since it doesn't work for me, I'll use the former. But does anyone have any idea of the speed difference? I'd assume it is negligible in such a simple example.
    Thanks!
    Solved!
    Go to Solution.

    Yep-
    You hit a point that's frustrated me a time or two as well (and incidentally, caused some hair-pulling that I can ill afford)
    The hint is in the help file:
    for Match regular expression "The Match Regular Expression function gives you more options for matching
    strings but performs more slowly than the Match Pattern function....Use regular
    expressions in this function to refine searches....
    Characters to Find
    Regular Expression
    VOLTS
    VOLTS
    A plus sign or a minus sign
    [+-]
    A sequence of one or more digits
    [0-9]+
    Zero or more spaces
    \s* or * (that is, a space followed by an asterisk)
    One or more spaces, tabs, new lines, or carriage returns
    [\t \r \n \s]+
    One or more characters other than digits
    [^0-9]+
    The word Level only if it
    appears at the beginning of the string
    ^Level
    The word Volts only if it
    appears at the end of the string
    Volts$
    The longest string within parentheses
    The first string within parentheses but not containing any
    parentheses within it
    \([^()]*\)
    A left bracket
    A right bracket
    cat, cag, cot, cog, dat, dag, dot, and dag
    [cd][ao][tg]
    cat or dog
    cat|dog
    dog, cat
    dog, cat cat dog,cat
    cat cat dog, and so on
    ((cat )*dog)
    One or more of the letter a
    followed by a space and the same number of the letter a, that is, a a, aa aa, aaa aaa, and so
    on
    (a+) \1
    For Match Pattern "This function is similar to the Search and Replace
    Pattern VI. The Match Pattern function gives you fewer options for matching
    strings but performs more quickly than the Match Regular Expression
    function. For example, the Match Pattern function does not support the
    parenthesis or vertical bar (|) characters.
    Characters to Find
    Regular Expression
    VOLTS
    VOLTS
    All uppercase and lowercase versions of volts, that is, VOLTS, Volts, volts, and so on
    [Vv][Oo][Ll][Tt][Ss]
    A space, a plus sign, or a minus sign
    [+-]
    A sequence of one or more digits
    [0-9]+
    Zero or more spaces
    \s* or * (that is, a space followed by an asterisk)
    One or more spaces, tabs, new lines, or carriage returns
    [\t \r \n \s]+
    One or more characters other than digits
    [~0-9]+
    The word Level only if it begins
    at the offset position in the string
    ^Level
    The word Volts only if it
    appears at the end of the string
    Volts$
    The longest string within parentheses
    The longest string within parentheses but not containing any
    parentheses within it
    ([~()]*)
    A left bracket
    A right bracket
    cat, dog, cot, dot, cog, and so on.
    [cd][ao][tg]
    Frustrating- but still managable.
    Jeff

  • Can somebody help me in getting some good material for Regular Expressions and IP Community list

    can somebody help me in getting some good material for Regular Expressions and IP Community list

    I'm not sure what you mean by "IP Community list", but here are 3 reference sites for Regular Expressions:
    Regular Expression Tutorial - Learn How to Use Regular Expressions
    http://www.regular-expressions.info/tutorial.html
    Regular Expressions Cheat Sheet by DaveChild
    http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
    Regular Expressions Quick Reference
    http://www.autohotkey.com/docs/misc/RegEx-QuickRef.htm

  • Find text using regular expression and add highlight annotation

    Hi Friends
                       Is it possible to find text using regular expression and add highlight annotation using plugin

    A plugin can use the PDWordFinder to get a list of the words on a page, and their location. That's all that the API offers for searching. Of course, you can use a regular expression library to work with that word list.

  • Regular expressions and JTextArea

    Hi,
    The aim of the code below is to match the String "one" to the text that is entered
    in the JTextArea (editor) using the regular expression syntax. When i add a String ("one")
    as an argument to p.matcher then the flow of control is passed
    to the System.out.println method, to indicate that the regular expression is mathced.
    However, when i add editor (editor = JTextArea)
    as an argument to p.matcher then the flow of control is not passed to the System.out.println
    method. Since, what is added to the JTextArea (editor) is a String of text, why does this not work?
    and what method or alteration can be used in order to get this working??
    Thanks very much for any help in advance
    Much appreciated
    import java.util.*;
    import java.util.regex.*;
    import java.io.*;
    import java.lang.*;
    import javax.swing.*;
    public class ExpressReg{
    public String Edit;
    public ExpressReg(String editor){
    editor = Edit;
    String regrex = "one";
    Pattern p = Pattern.compile(regrex);
    Matcher m = p.matcher(editor);
    boolean result = m.matches();
    while(result){
    System.out.println("this works");
    }

    you have your assignment round the wrong way, i think
    u want Edit = editor ?Cheers for the help,
    much appreciated

  • Regular expression and XML

    Hello,
    I have an XML file containing regular expressions and i parse the file, extract the pattern from it and search for it using java regex package. The problem is it works fine when patterns are words but when the pattern is something like
    write \\d+ (write followed by a space followed by one or mre digits) it doesn't work.
    I wrote the same code but with the pattern embedded in it,ie. without using XML and it worked. But when extracting with XML it fails.
    Also if the pattern is write[0-9] it only extracts write[0-9 and gives an error of no closing bracket.
    Could anyone please tell me what i am missing out
    Thank you

    thank you for your replies. Well i have still no got over the problem so i am posting my code here and hoping it can get solved
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    import java.io.*;
    import java.util.regex.*;
    class textextractor extends DefaultHandler{
         boolean regex=false;
    public void startElement(String namespaceURI,String localName,String qn,Attributes attr)
              if(localName.equals("REGEX"))
               regex=true;
    public void characters(char [] text,int start,int length)throws SAXException {
              String t=new String(text,start,length);
              boolean flag=false;
              if(regex==true)
                Pattern pattern;
                  String w=new String(t);
              pattern = Pattern.compile(w);
              Matcher matcher;
              matcher=pattern.matcher("there is a bat   read  write 13    error at line ");
              while(matcher.find())
               flag=true;
               System.out.println("I found the text \"" + matcher.group() +"\" starting at index "
               + matcher.start() +"and ending at index " + matcher.end() + ".");
             if(!flag)
               System.out.println("not found");
             regex=false;
    public class saxt2 {
         public static void main(String args[]) {
              try {
                    XMLReader parser= XMLReaderFactory.createXMLReader();
                    ContentHandler handler=new textextractor();
                    parser.setContentHandler(handler);
                                    parser.parse("d:\\regex.xml");
                  }catch (Exception e) {
                   System.err.println(e);
    }The xml file is
                      <RegularExpression>
                      <REGEX>write</REGEX>
                      <REGEX>write \\d+</REGEX>
                      <REGEX>read[0-9]</REGEX>
                      </RegularExpression>by running the code you can see that write is found,write \\d+ doesn't match write 13 in the string and read[0-9] gives and error.
    Any help will be greatly appreciated

  • Regular Expressions and Double Byte Characters ?

    Is it possible to use Java Regular Expressions to parse
    a file that will contain double byte characters ?
    For example, I want a regular expression to match the following line
    tag="double byte stuff" id="double byte stuff"

    The comments on the bytes/strings were helpful. Thanks.
    But I'm still confused as to what matching pattern could be used.
    For example a pattern like:
    [A-Za-z]
    I assume would not match any double byte characters.
    I also assume the following won't work either:
    [\\p{Alpah}]
    because it is posix - US-ASCII only.
    So how do you say "match the tag, then take any characters,
    double byte, ascii, whatever, then match the text tag - per the
    original example ?

  • Regular Expression and PL/SQL help

    I am using Oracle 9i, does 9i support regular expression? What functions are there?
    My problem is the birth_date column in my database comes from teleform ( a scan program that reads what people wrote on paper), so the format is all jacked up.... 50% of them are 01/01/1981, 10% are 5/14/1995, 10% are 12/5/1993, 10% are 1/1/1983, 10% are 24-JUL-98. I have never really used regular expression and pl/sql, can anybody help me convert all of them to 01/01/1998?
    Does Oralce 9i support regular expression? What can I do if oralce 9i does not support regular expression? Thank you very much in advance.

    9i doesn't support regular expressions (at least not in the 10g regular expressions sense. There is an OWA_PATTERN_MATCH package that has some facilities for regular expressions). But it doesn't look like this is a regular expressions problem.
    Instead, this is probably a case where you need to
    - enumerate the format masks you want to try
    - determine the order you want to try them
    - write a small function that tries each format mask in succession until one matches.
    Of course, there is no guarantee that you'll ever be able to convert the data to the date that the user intended because some values will be ambiguous. For example, 01/02/03 could mean Feb 1, 2003 or Jan 2, 2003 or Feb 3, 2001 depending on the person who entered the data.
    Assuming you can define the order, your function would just try each format mask in turn until one generated a valid date, i.e.
    BEGIN
      BEGIN
        l_date := TO_DATE( p_string_value, format_mask_1 );
        RETURN l_date;
      EXCEPTION
        WHEN OTHERS THEN
          NULL;
      END;
      BEGIN
        l_date := TO_DATE( p_string_value, format_mask_2 );
        RETURN l_date;
      EXCEPTION
        WHEN OTHERS THEN
          NULL;
      END;
      BEGIN
        l_date := TO_DATE( p_string_value, format_mask_3 );
        RETURN l_date;
      EXCEPTION
        WHEN OTHERS THEN
          NULL;
      END;
      BEGIN
        l_date := TO_DATE( p_string_value, format_mask_N );
        RETURN l_date;
      EXCEPTION
        WHEN OTHERS THEN
          NULL;
      END;
      RETURN NULL;
    END;Justin

  • Difference between regular expressions and spry character masking?

    Hi,
    This is my first time writing my own regular expressions.  Often times though, they seem to work in various testing widgets, but then they do not perform as expected in Spry.  I have no idea how to even begin to debug this.
    For example, this string:
    ^\#?[A-Fa-f0-9]{3}([A-Fa-f0-9]{3})?$
    Does a perfect job enforcing hex colors in a regexp testing widget.  But it doesn't work in spry.  It won't let me type a darn thing in.
    Can somebody throw me a bone here?

    Hi!
    Thank you for the response.  I read that article prior to posting and it seems to relate more to Spry's custom pattern function rather than regular expressions.  Here's the code I have:
    <script type="text/javascript">
         <!--     
              var text_1 =
              new Spry.Widget.ValidationTextField(
                   "text_1",
                   "none",
                   {regExpFilter:/^#[A-Fa-f0-9]{6,};$/,
                   useCharacterMasking:true,
                   validateOn:["change"]})
         //-->
    </script>
    Expected behavior:  I should be able to type in a valid hex color and have Spry perform validation.
    Actual behavior:  I can't type anything in, at all.  I immediately get the invalid Spry feedback (in my case a little red .png image and an error message).
    Simpler expressions like this work fine in Spry:
                        <script type="text/javascript">
         <!--
              var text_1 =
                   new Spry.Widget.ValidationTextField(
                   "text_1",
                   "none",
                   {regExpFilter:/[a-z]/,
                   useCharacterMasking:true,
                   validateOn:["change"]})
         //-->
    </script>
    I think if I can figure out what the special rules are for one somewhat robust regular expression in Spry, then I will be off and running.
    Can anyone help?
    Scott

  • Juniper MX Regular expressions and user permissions ACS 5.4

    Hi everyone!
    Im having some trouble with regular expressions and permissions on our Juniper MX routers through ACS 5.4, and i would like some insight/help/poitners!!
    We have a team of engineers that should only have read only permissions (important: show configuration) and also be able to just change the description on interfaces.
    Thus far with the following regular expressions set for the shell profile they are going through i have managed the above, however the problem is when an engineer inputs "Show configuration", only the interfaces descriptions configuration is shown! The rest of the configuration will not be printed.
    deny-commands1=.*.
    allow-commands1=configure
    deny-configuration1=.*.
    allow-commands2=interfaces .*. description .*$
    allow-configuration1=interfaces .*. description .*$
    allow-commands2=show configuration.*
    allow-commands3=show configuration
    (some of these regex i know that are not needed, i was just playing around to check everything before posting)
    Any pointers as to why or how to resolve this?
    example output with the above:
    show configuration
    ## Last commit: 2014-01-09 09:34:44 EET by someone
    interfaces {
        xe-0/0/0 {
        xe-0/0/1 {
            description xxxx;
        xe-0/1/0 {
            description xxxx;
        xe-0/1/1 {
            description xxxx;
        xe-0/2/0 {
            disable;
        xe-0/2/1 {
            description xxxx;
        xe-0/3/0 {
            description xxxx;
        xe-0/3/1 {
            description xxxx;
        ae0 {
            description "xxxx";
        ae1 {
            description xxxx;
        demux0 {
        lo0 {
    {master}
    Thanks in advance!
    Spyros

    You are absolutely right!!  I was doing research online after posting the above.  The correct RADIUS attribute to use is actually CVPN3000/ASA/PIX7.x-Group-Based-Address-Pools.  Then create the pool in ASA, and call that pool's name in ACS under that RADIUS attribute.  Someone explained this perfectly in this community before.  Much appreciate your answer!
    Here's from another post last year:
    ACS  5 does not have the feature of IP pools. Logically its always good to  setup pools locally on vpn server and if you want user to pick ip from  specific local pool you can configure acs to push that attribute.
    On ACS Go to > Policy Elements  -> Network Access ->   Authorization Profiles -> Create ->
    Name of the Policy ->Dictionary Type: Radius-Cisco VPN 3000/ASA/PIX7.x
    Attribute Type : CVPN3000/ASA/PIX7.x-Group-Based-Address-Pools
    Attribute Type: String
    Attribute Value : Static MYPOOL (Name of the Pool which is defined on the ASA)
    Access Policies ->Default Network Access -> Authorization ->  Create -> Under result section call the Authorization p

  • Need help for a more complicated regular expression

    Hi everyone,
    I got another more complicated one here.
    I need to split  '+0,+0.00000000E+000, -4.76517000E+001,-4.64744200E+001,-6.18140500E+001,-5.93055600E+001' by ',' into an array without '+0,+0.00000000E+000'.
    I am using a regular expression as  '[+-]([0-9]+[1-9]+)[E][+]\d' but it failed to, just wondering what is happening there.
     Any idea is well appreciated,
    Thanks,
    +Kunsheng
    Message Edited by Kunsheng Chen on 03-05-2009 05:09 PM
    Solved!
    Go to Solution.
    Attachments:
    regular.vi ‏33 KB

    First, don't bother with regular expressions. Use the function Spreadsheet String to Array with a commas as the delimiter, %f as the format string, a 1D array of floats as the array type. Next, delete the first two elements from the results and you're done.
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • Regular expression and output format

    hi all,
    i have following scenario-
    regular expression: [0-9]{3}-[0-9]{3}-[0-9]{4}
    generated value by the above regular expression: 123-234-6789
    output format to display the generated above value: xxx-xxx-$1
    now i need to display the generated value (123-234-6789) in the specified output format (xxx-xxx-$1) and the final output will be xxx-xxx-6789
    how is it possible?
    Note: here regular expression and output format can vary
    br,
    bashar

    Hi, Bashar
    You can solve this problem by using the Data Masking Technique.
    Masking data means replacing certain fields with a Mask character (such as an X). This effectively disguises the data content while preserving the same formatting on front end screens and reports. For example, a column of credit card numbers might look like:
    4346 6454 0020 5379
    4493 9238 7315 5787
    4297 8296 7496 8724
    and after the masking operation the information would appear as:
    4346 XXXX XXXX 5379
    4493 XXXX XXXX 5787
    4297 XXXX XXXX 8724
    The masking characters effectively remove much of the sensitive content from the record while still preserving the look and feel. Take care to ensure that enough of the data is masked to preserve security.
    It would not be hard to regenerate the original credit card number from a masking operation such as: 4297 8296 7496 87XX since the numbers are generated with a specific and well known checksum algorithm.
    Best Regards,
    Mahfuz Khan

  • Use a regular expression to do this...

    I need to process this line : "STRTsomeEND.STRTsome2END.STRTsome3END"
    to get an array with this values :
    String[] processedLine = {
    {"STRTsomeEND."}
    {"STRTsome2END."}
    {"STRTsome3END."}
    I tried to use this regular expression to do the work: (STRT[.*]END.)+ but doesn't work. Also I tried with this expresion STRT[.*]END. But I only got the first ocurrence ("STRTsomeEND") .
    Can anybody help me?

    zkropotkine wrote:
    1) "." is a regex flag.I saw in the table and it said that the "." symbol doesn't need the escape: )
    when you ask a question and then someone gives you advice you should
    give them the benefit of the doubt (for at least a little while).
    did you take a moment to try to understand what i was saying about escaping the "."?
    anyway, your regex should be:
    (START)(.*?)(END)\ \ .
    the "?" after the "\*" means "reluctant". you dont want the ".\*" to grab up everything.
    with the reluctant modifier "?" the regex should stop and grab the first available "END".
    and finally, if you meant the "." at the end of "STARTsomethingEND." literally then:
    you need to escape the "."

  • Assistance with Regular Expression and Tcl

    Assistance with Regular Expression and Tcl
    Hello Everyone,
      I recently began learning Tcl to develop scripts for automating network switch deployments. 
    In my script, I want to name the device with a location and the last three octets of the base mac address.
    I can get the Base MAC address by : 
    show version | include Base
     Base ethernet MAC Address       : 00:00:00:DB:CE:00
    And I can get the last three octets of the MAC address using the following regular expression. 
    ([0-9a-f]{2}[:-]){2}([0-9a-f]{2}$)
    But I have not been able to figure out how to call the regular expression in the tcl script.
    I have checked several resources but have not been able to figure it out.  Suggestions?
    Ultimately, I want to set the last three octets to a variable (something like below) and then call the variable when I name the switch.
    set mac [exec "sh version | i Base"] (include the regular expression)
    ios_config "hostname location$mac"
    Thanks for any assistance in advance.
    Chris

    This worked for me.
    Switch_1(tcl)#set result [exec show ver | inc Base]   
    Base ethernet MAC Address       : 00:1B:D4:F8:B1:80
    Switch_1(tcl)#regexp {([0-9A-F:]{8}\r)} $result -> mac
    1
    Switch_1(tcl)#puts $mac                               
    F8:B1:80
    Switch_1(tcl)#ios_config "hostname location$mac"      
    %Warning! Hostname should contain at least one alphabet or '-' or '_' character
    locationF8:B1:80(tcl)#

Maybe you are looking for

  • Sat P10-722: How to switch to TV - S-Video

    can anyone please answer me this quick question? i have a satellite p10-722 with an s-video out, if i were to connect a normal s-video cable to this then to my tv would i be able to view my laptop on my t.v? thank you for any answers

  • I have bad service inside my house, how can I get that fixed with Verizon

    I can practically see two Cell Towers within 1/2 mile of my house but when I get a phone call or make a call out, the service is fine for 5 seconds and then it really breaks up? I live in the SW with Stucco and Metal Mesh but have owned homes before

  • New Mac Pro: Jumbo Frames available?

    Hi, i intend to buy a new mac pro - but beeing forced to use jumbo-frames in my network. Is this network-packet-frame-size (9000) working on new mac pro´s ? Thank you in advance for any information about it. BR Peter

  • After install Mavericks I can't turn off my MacBook Pro from the power button.

    Dear all, prior to install Mavericks in my MacBook Pro, when I pushed the power button it appeared a dialog box which gave me the option to turn off the copmuter choosing the right option. After the installation of Mavericks,and obviuosly having the

  • How to stop the spiral?

    How do I stop the swirling spiral on Macbook air with new OS?