Regex or String methods

Hi
Im wondering how more experienced Java developers would approach this.
I have a parser which receives Strings according to the irc-protocol.
servername PRIVMSG #channel :Hello worldAlmost every message is defined by the second word in the String. So its easy to just do String.split(" ") ... check the messagetype and start working with the other elements. Of course things gets a bit out of hand with compareTo(), IndexOf(), Substring() ... and all the other String methods.
How would u use regex for this if u had to? I see this as exercise ... slower code, more work ... doesnt matter and its a plus learning more about regex.
Example ... the line above, how would u use regex to check the messagetype "privmsg" ... channel "#channel" and the messagepart after the ':' etc ...
many thanks in advance

I wouldn't use regex, but split indeed, since I'd
have very easy access to each part of the message.
Anyway, since you want to learn regex: why don't you
grab the Pattern API and read and try a little
yourself? Nothing teaches you better than finding out
yourself.Well yes regexes are nice easy and clean. And a wevy usefull if you learn them cos it gives you unlimited power of string manipulation.
But at a high cost.
It is verry important to make the right choice (regex or string methods) becouse it will decide how good your code looks and work.
If the pattern that need to be parsed is simple and cam be done using string methods (including string tokenizer) regex is not the way to go.
Normally when handling simple text patterns like above the string methods will perform about 5 times faster than regexes.
So my recomendation is.
If you are doing this for learning do it both ways and practice both regexes and string methods. Becouse in the industry you have know the both well.
If you are doing this for some sort of a project and performance is a significant quality factor you need to use string methods in this perticuler situation.
Above pattern can easilly broaken down using a combination of substring, index of and string tokenizer.

Similar Messages

  • "Import string" method not supported in LabVIEW 7.1

    We have made an application that support multi-language (English, French, etc.). In LabVIEW 6.1, we used the "import string" VI method to support this option. The method was executed just before to open front panel. The code was based on this example found in NI Developer Zone:
    Translation/Localization Tools in LabVIEW
    (http://sine.ni.com/apps/we/niepd_web_display.disp​lay_epd4?...
    But surprise in version 7.1, this method can't be loaded without the diagram block. So the built application doesn't support it! It works only in the development interface. Why this change?
    If someone has an idea to solve this, let me know.

    If you build that example into an EXE under LabVIEW 7.1, it should work fine as long as you add the non top-level VIs as Dynamic VIs and add the language files as Support Files when you create the executable, making sure to specify in "Custom Destinations" that you want the string files to end up in the same directory as the EXE.
    Your point about the method requiring the block diagram is correct, according to the help for the method. However, I think the diagrams will be available to the run-time engine as long as you haven't purposefully removed them prior to creating the EXE in the manner described above. Maybe someone else can chime in on this point, because I know the App Builder changes a lot with every new major LabVIEW version (and sometimes, with minor versions too!).
    In any case, I just did a test where I downloaded the example you referenced, created a .BLD file as I indicated above, and got a successful executable that was able to use the Import VI Strings method to load the desired language at run-time.
    Regards,
    John

  • Import & Export Strings method

    Hi,
    I have a multilanguage application. I have used export & import
    strings methods. I have one .txt file for each language but when I
    modify something in my vi I must export all again and then modify the
    tags again for each language file... Is there a way that I can modify
    my vi and I don't have to export all again?
    Thanks,
    ToNi.

    As far as i know you need to export strings again only if you have made any changes on front panel.
    exported file is nothing but a xml file so that you can manually edit it instead of exporting everything again (helpfule if you have done very small changes on front panel)
    Tushar Jambhekar
    [email protected]
    Jambhekar Automation Solutions
    LabVIEW Consultancy, LabVIEW Training
    Rent a LabVIEW Developer, My Blog

  • NullPointerException on String methods

    All,
    I am trying to get date values on the fly and add them to my sql statement. I have a DateWorker class that provides month, day of month and year.
    When I use the class in another class, I get NullPointerException. These are just plain ol' String methods, why are they giving me problems. When I run the code on its won, it works fine.
    Code:
    package mybeans;
    import java.util.Date;
    import java.text.SimpleDateFormat;
    import java.util.HashMap;
    import java.util.Calendar;
    public class DateWorker {
    public DateWorker dateWorker;
         public DateWorker(){
              dateWorker = new DateWorker()
         public static void main(String[] args){
              String m = dateWorker.getMonth();
              String dm = dateWorker.getDayOfMonth();
              String dw = dateWorker.getDayOfWeek();
              String y = dateWorker.getYear();
              System.out.println("day of week " + dw + "<BR>");
              System.out.println("day of month" + dm + "<BR>");
              System.out.println("month " + m + "<BR>");
              System.out.println("year " + y + "<BR>");
         //get a Calendar instance.
         private Calendar cal = Calendar.getInstance();
         //gets the current month
         public String getMonth(){
         int x = cal.get(Calendar.MONTH) + 1;
         String s = String.valueOf(x);
         return s;
         //gets the current day of month
         public String getDayOfMonth(){
              int x = cal.get(Calendar.DAY_OF_MONTH);
              String s = String.valueOf(x);
              return s;
         //gets the current day of week
         public String getDayOfWeek(){
              int x = cal.get(Calendar.DAY_OF_WEEK) -1;
              String s = String.valueOf(x);
              return s;
         //gets the current year
         public String getYear(){
              int x = cal.get(Calendar.YEAR);
              String s = String.valueOf(x);
              return s;
    Edited by: ink86 on Oct 8, 2007 12:57 PM

    package mybeans;
    import java.util.Date;
    import java.text.SimpleDateFormat;
    import java.util.HashMap;
    import java.util.Calendar;
    public class DateWorker {
         public static void main(String[] args){
              DateWorker dateWorker = new DateWorker();
              String m = dateWorker.getMonth();
              String dm = dateWorker.getDayOfMonth();
              String dw = dateWorker.getDayOfWeek();
              String y = dateWorker.getYear();
              System.out.println("day of week " + dw + "<BR>");
              System.out.println("day of month" + dm + "<BR>");
              System.out.println("month " + m + "<BR>");
              System.out.println("year " + y + "<BR>");
         //get a Calendar instance.
         Calendar cal = Calendar.getInstance();
         //gets the current month
         public String getMonth(){
         int x = cal.get(Calendar.MONTH) + 1;
         String s = String.valueOf(x);
         return s;
         //gets the current day of month
         public String getDayOfMonth(){
              int x = cal.get(Calendar.DAY_OF_MONTH);
              String s = String.valueOf(x);
              return s;
         //gets the current day of week
         public String getDayOfWeek(){
              int x = cal.get(Calendar.DAY_OF_WEEK) -1;
              String s = String.valueOf(x);
              return s;
         //gets the current year
         public String getYear(){
              int x = cal.get(Calendar.YEAR);
              String s = String.valueOf(x);
              return s;
         }

  • Urgent!!!   Problem on the String method and File method

    I would like to ask two questions:
    (1) From the String method, it can use .equals() method to compare two strings whether two string exactly equal or not. But what method can i use to compare two strings see whether any words exists in the string?
    (2) From the following code,
    Java.io.File outFile = new java.io.File("TestProg.java");If i would like to use a variable (e.g. let the variable be name) instead of the filename "TestProg.java", do you know how to revise the above code??
    If i write as following, is it correct???
    Java.io.File outFile = new java.io.File(""+name+"");Please help!!!

    1- To check whether a word (sunstring) exists in a longer string, you can use the following String method:
    indexOf(substring) on the string that you are searching. If the word does not exist, -1 is returned.
    2- yes you can provide a variable (of type string) in the constrcutor of File.

  • Why is String method called not Object method

    In the below program ::
    class Test
         public void callMethod(Object o)
              System.out.println("Object Method Called");
         public void callMethod(String s)
              System.out.println("String Method Called");
         public static void main(String[] args)
              Test t = new Test();
              t.callMethod(null);
    }

    In the below program ::
    class Test
         public void callMethod(Object o)
              System.out.println("Object Method Called");
         public void callMethod(String s)
              System.out.println("String Method Called");
         public static void main(String[] args)
              Test t = new Test();
              t.callMethod(null);
    }If more than one method could be called the most specific one is called. Since a String is an Object then the String one gets called.

  • Can I use to.String() method with NamedCache

    Hi,
    I have a distributed cache. Can I use to.String() method to print the contents of cache on the console. In my case it is not working..Do I neet to import anything?
    NamedCache cache = CacheFactory.getCache("Test");
    cache.put("hello", "world");
    System.out.println(cache.toString());
    Thanks,
    Chaya

    Hi Chaya,
    Assuming that I understand your question correctly, each JVM has the same view of the cache if you're using a distributed (or optimistic, replicated, ...) cache. So when you add records from one JVM, they are visible to all the JVMs immediately (if you start up a new JVM, it will join the cluster and share the data as well).
    So if you populate a named cache from JVM1, you can simply execute the display code (from my previously reply) in any JVM connected through Coherence, and it will display the entire contents of the logical named cache.
    Jon Purdy
    Tangosol, Inc.

  • String method indexOf

    I have to show the number of occurances of a character in a string.
    I chose the letter 'a' - here is my code, my problem is i only get one occurance, how do i show all indexes of 'a'?
    thanks,
    barb
    // Java extension packages
    import javax.swing.*;
    public class IndexOf {
    public static void main( String args[] )
    String text ="This class is really hard \n" +
         "I'm glad I did well on the midterm \n" +
         "It took a long time.";
         String output1 =      "'This class is really hard.\n" +
                   "I'm glad I did well on the midterm.\n" +
                   "It took a long time.'"+ "\n\n";
         int pos;
    int count = 0;
    pos = text.indexOf ('a');
    while ( pos != -1)
              count++;
              pos = text.indexOf ('a', pos+1);
    // test indexOf to locate a character in a string
    String output2 = "'a' is located at index " + text.indexOf ('a') +
    text.indexOf('a');
    JOptionPane.showMessageDialog( null, output1 + output2,
              "String method indexOf",
    JOptionPane.INFORMATION_MESSAGE );
    System.exit( 0 );
    } // end class String IndexOf

    // Try this.
    String text ="This class is really hard \n" +
    "I'm glad I did well on the midterm \n" +
    "It took a long time.";
    String result="";
    for (int i=0; i<text.length(); i++)
    { if  (text.charAt(i)=='a')result += "Index: " + i + System.getProperty( "line.separator" ); }
    System.out.print(result);

  • Return from String method

    Hi
    Can anyone help me:
    I have a class with a String method.
    The returned value for the method is calculated in a thread. Since I have to share the same literal for the String and run methods, the returned value for the String method is not the value that the run method is supposed to calculate for me. It just wouldn't wait until it's ready.
    What should I do? Can I block the String method to return the string until the run method is ready?

    Look up Thread.waitFor()

  • Which String method would be used to...

    Which string method (maybe it's not even a string method) would be used to change user input for example from:
    User input: Brandon Bell
    Changed to Bell, Brandon
    Thanks.
    Brandon Bell

    Which string method (maybe it's not even a string
    method) would be used to change user input for
    example from:
    User input: Brandon Bell
    Changed to Bell, Brandon
    Your question is very vague. What are the exact requirements? Are you assuming that the inputted string is a first name and a last name, separated by a space, and you want to change it to last name comma first name?
    If so, the methods indexOf and substring will be enough for a first, naive implementation. With that in place you might want to ask yourself:
    Will you allow the first name to have one or more spaces? Will you allow the last name to have one or more spaces? Etc, etc.

  • String method compareTo

    I am trying to write a program that compares two strings and comes back with the result of wether the first string is "less then", "equal to" or "more then" the second string. I have written the code and will post it. I am only coming across one error, it is saying it cannot resolve the variable "value" in....
    displayField.setText("The first string is "+ value +" the secone one!");
    here is the code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CompareWindow extends JFrame{
         private JLabel string1Label,string2Label;
         private JTextField string1Field,string2Field,displayField;
         private JButton exitButton;
    public CompareWindow()
    super("String method compareTo");
    ActionEventHandler handler=new ActionEventHandler();
    Container container = getContentPane();
    container.setLayout(new FlowLayout() );
    string1Label=new JLabel("Enter first string");
    string1Field=new JTextField(20);
    string1Field.addActionListener(handler);
    container.add(string1Label);
    container.add(string1Field);
    string2Label=new JLabel("Enter second string");
    string2Field=new JTextField(20);
    string2Field.addActionListener(handler);
    container.add(string2Label);
    container.add(string2Field);
    displayField=new JTextField(30);
    displayField.setEditable(false);
    container.add(displayField);
    exitButton=new JButton("Exit");
    exitButton.addActionListener(handler);
    container.add(exitButton);
    public void displayCompare()
    displayField.setText("The first string is "+ value +" the secone one!");
    public static void main(String args[])
    CompareWindow window = new CompareWindow();
    window.setSize(400,140);
    window.setVisible(true);
    private class ActionEventHandler implements ActionListener{
    String first=string1Field.getText();
    String second=string2Field.getText();
    int compare1=0;
    String value;
    public void actionPerformed(ActionEvent event)
    String first=string1Field.getText();
    String second=string2Field.getText();
    int compare1=0;
    String value;
    if (event.getSource()==exitButton)
    System.exit(0);
    else if (event.getSource()==string1Field) {
    compare1=first.compareTo(second);
    else if (event.getSource()==string2Field) {
    compare1=first.compareTo(second);
    if (compare1<0){
    value="less then";
    else if (compare1==0){
    value="equals";
    else if (compare1>0){
    value="greater then";
    displayCompare();
    }Any help will be appreciated.

    The variable value is not accessible displayCompare method.You will need to pass it as parameter to that displayCompare method or move the declaration to the outer Class i.e. CompareWindow.

  • Regex in String.replaceall()

    I wanted to remove ewg text from following lines completely.
    ewg#First line
    ewg#Second line
    ewgThird line
    For this i have used String class replace all method as follows:
    StringBuffer sb = new StringBuffer(returnString.replaceAll("(?i)\\bentfw\\b",""));The problem is this code is replacing only first two lines not the third line. Please help me

    returnString.replaceFirst("(?i)^ewg","")i tried this but its not removing ewg at allSeems to work just fine for me:
    String[] lines = new String[]{"ewg#First line",
    "ewg#Second line", "ewgThird line", "a line not
    starting with ewg"};
    String regex = "(?i)^ewg";
    for (String line : lines) {
         System.out.println(line.replaceFirst(regex, ""));
    sorry for long delay reply.
    i still couldnt solve this problem.
    i am not using any string array but a single string that separates these three lines with \n

  • Need some help with the String method

    Hello,
    I have been running a program for months now that I wrote that splits strings and evaluates the resulting split. I have a field only object (OrderDetail) that the values in the resulting array of strings from the split holds.Today, I was getting an array out of bounds exception on a split. I have not changed the code and from I can tell the structure of the message has not changed. The string is comma delimited. When I count the commas there are 26, which is expected, however, the split is not coming up with the same number.
    Here is the code I used and the counter I created to count the commas:
    public OrderDetail stringParse(String ord)
    OrderDetail returnOD = new OrderDetail();
    int commas = 0;
      for( int i=0; i < ord.length(); i++ )
        if(ord.charAt(i) == ',')
            commas++;
      String[] ordSplit = ord.split(",");
      System.out.println("delims: " + ordSplit.length + "  commas: " + commas + "  "+ ordSplit[0] + "  " + ordSplit[1] + "  " + ordSplit[2] + "  " + ordSplit[5]);
    The rest of the method just assigns values to fields OrderDetail returnOD.
    Here is the offending string (XXX's replace characters to hide private info)
    1096200000000242505,1079300000007578558,,,2013.10.01T23:58:49.515,,USD/JPY,Maker,XXX.XX,XXX.XXXXX,XXXXXXXXXXXXXXXX,USD,Sell,FillOrKill,400000.00,Request,,,97.7190000,,,,,1096200000000242505,,,
    For this particular string, ordSplit.length = 24 and commas = 26.
    Any help is appreciated. Thank you.

    Today, I was getting an array out of bounds exception on a split
    I don't see how that could happen with the 'split' method since it creates its own array.
    For this particular string, ordSplit.length = 24 and commas = 26.
    PERFECT! That is exactly what it should be!
    Look closely at the end of the sample string you posted and you will see that it has trailing empty strings at the end: '1096200000000242505,,,'
    Then if you read the Javadocs for the 'split' method you will find that those will NOT be included in the resulting array:
    http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)
    split
    public String[] split(String regex)
    Splits this string around matches of the given regular expression.  This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
    Just a hunch but your 'out of bounds exception' is likely due to your code assuming that there will be 26 entries in the array and there are really only 24.

  • Strange about invoking web service method declared “string  method(void)”;

    Dear forum readers
    I’m experimenting with OpenESB and web services. I’ve create a simple web service using NetBeans 6.1. The method consists of a single method, getTime, that is declared:
    String getTime()
    My current experiment is to invoke this method from a BPEL-process using the “Invoke” process object. The strange thing is that it seems like I have to provide a “dummy” inbound variable from the BPEL-designer even though the method doesn’t take any parameters. I include a snippet from the BPEL process below which includes the section where I set the dummy GetTimeIn-variable and then invokes the WS method getTime().
    <assign name="Assign2">
    <copy>
    <from>'DummyValue'</from>
    <to variable="GetTimeIn" part="parameters"/>
    </copy>
    </assign>
    <invoke name="Invoke1" partnerLink="PartnerLink1" operation="getTime" xmlns:tns="http://ws/" portType="tns:MyWebService" outputVariable="GetTimeOut" inputVariable="GetTimeIn"/>
    If I don’t initiate the dummy variable or remove it altogether, I can’t successfully call the method. If I include the dummy in-parameter the call works just fine and I get back the current time as a string.
    I must admit that I’m still a rookie to web services, especially when calling them from a BPEL-process, so it may be a very trivial reason for this behaviour. Anyway, any help on this matter would be greatly appreciated.
    Regards, Ola

    Thank you both for the response. Regarding Rennay’s posting I have an additional question. When I create a new web service I don't have the "Document Literal" option nor a "Concrete Configuration" tab. I've created the web service using the "Web Application" project type and then adding a web service using the "Web Service..." wizard. This wizard doesn't have the configuration properties you mention, but if I add a WSDL-file to a BPEL-project the wizard has the properties you mention.
    Is it possible to create a web service, programmed as an ordinary Java-class, from an existing WSDL-file? In that case it may solve the problem with the “Document Literal” property. Currently I don’t know any other way to create such a web-service other than the through the web service wizard in a web application project. Of course, it’s possible to craft it from scratch but that’s to much work to be practical.
    Regards, Ola

  • Regex with strings that contain non-latin chars

    I am having difficulty with a regex when testing for words that contain non-latin characters (specifcally Japanese, I haven't tested other scripts).
    My code:
    keyword = StringUtil.trim(keyword);
    //if(keywords.indexOf(keyword) == -1)
    regex = new RegExp("\\b"+keyword+"\\s*;","i");
    if(!regex.test(keywords))
    {Alert.show('"'+keywords+'" does not contain "'+keyword+'"'); keywords += keyword + "; ";}
    Where keyword is
    日本国
    and keywords is
    Chion-in; 知恩院; Lily Pond; Bridge; 納骨堂; Nōkotsu-dō; Asia; Japan; 日本国; Nihon-koku; Kansai region; 関西地方; Kansai-chihō; Kyoto Prefecture; 京都府; Kyōto-fu; Kyoto; Higashiyama-ku; 東山区; Places;
    When the function is run, it will alert that keywords does not contain keyword, even though it does:
    "Chion-in; 知恩院; Lily Pond; Bridge; 納骨堂; Nōkotsu-dō; Asia; Japan; 日本国; Nihon-koku; Kansai region; 関西地方; Kansai-chihō; Kyoto Prefecture; 京都府; Kyōto-fu; Kyoto; Higashiyama-ku; 東山区; Places; " does not contain "日本国"
    Previously I was using indexOf, which doesn't have this problem, but I can't use that since it doesn't match the whole word.
    Is this a problem with my regex, is there a modifier I need to add to enable unicode support or something?
    Thanks
    Dave

    ogre11 wrote:
    > I need to use refind to deal with strings containing
    accented characters like
    > ?itt? l?su, but it doesn't seem to find them. Also when
    using it with cyrillic
    > characters , it won't find individual characters, but if
    I test for [\w] it'll
    > work.
    works fine for me using unicode data:
    <cfprocessingdirective pageencoding="utf-8">
    <cfscript>
    t="Tá mé in ann gloine a ithe;
    Nà chuireann sé isteach nó amach
    orm";
    s="á";
    writeoutput("search:=#t#<br>for:=#s#<br>found
    at:=#reFind(s,t,1,false)#");
    </cfscript>
    what's the encoding for your data?

Maybe you are looking for

  • Is possible to capture the SP username of who is making submission of the data from an InfoPath 2010 form?

    Hi all, Does anyone know how to capture the SP username of who is making submission of the data from an InfoPath 2010 form? I looking to avoid the user need to type extra information like username/ manager name, etc; and then use code behind to be do

  • Error in creating windows 8.1 VMs from templates

    hello experts, I have created a template on  Windows 8.1 on SCVMM 2012 R2 (OS:Windows Server 2012) ,Now am try to create a Windows 8.1 VM on another Hyper-v Host where Windows Server 2012 r2 is installed but creation has got failed with error in job

  • Do I need to turn you in to the Attorney General????

    cancelled this service back in MAY 2015 and I hevv been charged 3times since then. I want my money back ASAP or I will file a claim with the Attorney Generals Office.  For your reference this is Case #: 02973654 

  • AS 2 Conundrum

    Happy Holidays everyone, I've looked at this problem a hundred times but cannot seem to see what's causing my problem.  I am looking at this ActionScript in my Flash file: import mx.transitions.Tween; import mx.transitions.easing.*; var tween_type =

  • Space.bar.is.not.responding.

    I.was.using.my.keyboard.and.I.think.I.have.hit.a.key.by.mistake.as.suddenly.my.space.bar.stopped.responding.this.is.the.only.way.I.can.type.anything.please.help