What is my String.split() not catching here?

Hello,
I am trying to implement the wordcount below. Most of the time it works great, the content matches the wc utility.
Occasionally though it splits in a manner that creates a whitespace word. Any suggestions? Is there a better algorithm to switch to? This had appeared to be a clean approach up until these issues.
public static int wordCounter(File inFile) throws FileNotFoundException, IOException{
          int count = 0;
          BufferedReader inReader = new LineNumberReader(new InputStreamReader(new FileInputStream(inFile)));
          try{               
               String lineString;
               String[] lineWords;     
               //while not the end of the file               
               while( (lineString = inReader.readLine()) != null){
                    lineString.trim();
                    lineWords = lineString.split("\\s+");
                    count += lineWords.length;                    
          } finally{
               //close the BufferedReader
               if(inReader != null){
                    inReader.close();
          //return the count
          return count;
     }

JustSomeGuy wrote:
chaddy_b wrote:
How do I add multiple expressions to my .split()?You don't! You make one expression that does it all.
^[ \t]+|[ \t]+$  <-- remove proceeding and trailing whitespaceNow you just have to figure out how to get your piece in there.
JSGJSG,
I think what the OP meant is s/he wants to know if s/he can use a single regex to split his/her string so that the string
"   a   b   c   "return only three tokens:
["a", "b", "c"]
// or
["   a", "b", "c"]I know of a rather "hackish" way to do it in one split(...) call, but I don't see how your suggestion will make this possible. As far as I can see, you're now just mimicing String's trim() method by using replaceAll(...).

Similar Messages

  • Regular expression not working for String.split()?

    hi, i have a String variable called 'table'.
    It has a bunch of chunks of data seperated by whitespace, whether it
    be spaces or carraige returns. Anyways, i want to split this up using
    the String.split function. i want to split it around whitespace.
    here is my code:
    String codes[] = table.split("\s");
    However, i'm getting back all nulls in the codes variable. What am i doing wrong?
    thanks

    split("\\s")\ is special both in Java String literals and in regex, so you need two of them.
    You'll probably also have to take an extra step it you don't want regex to stop at newlines. I forget the details, so check the docs.

  • I have brought a iphone 4 and the person i brought it from has not deleted her icloud account i need her pasword to delete it but hse wont give it to me what can i do how can i add my icloud account can you give me a reasonable answer please. thank you

    i have brought a iphone 4 and the person i brought it from has not deleted her icloud account i need her pasword to delete it but hse wont give it to me what can i do how can i add my icloud account can you give me a reasonable answer please. thank you.

    The seller needs to follow this procedure:
    http://support.apple.com/kb/TS4515
    If she refuses, then as Tim suggested the iPhone is probably stolen. You'll need to contact your local police department and ask how to proceed.
    Regards.

  • My iPhone 5 is not catching up my website, although having a big screen... What does it need to get the pages in auto mobile queries converting?

    my iPhone 5 is not catching up my website, although having a big screen... What does it need to get the pages in auto mobile queries converting?

    You need to code your web site to recognize the mobile browser and send a page that's actually usable when it does.

  • I have changed my password and still can't get homesharing to work. Get the message "Homesharing could not be activated because the account or password was incorrect. It's what I have used to sign in here!

    I  have changed my password and still can't get home sharing to work. Get the message "Home sharing could not be activated because the account or password was incorrect." It's what I have used to sign in here! Any help much appreciated.

    So I reset my Apple ID password. Which then stopped my MobileMe account from working. Hang on - these were 2 different accounts a while ago, with different passwords!!!
    So I have logged back in to MobileMe with my AppleID, and that's working again. After a short wait I can now create Home Sharing again.
    Folks, I think we have just had our Apple IDs merged with our MobileMe accounts!! With no consultation or warning.
    My guess is that this is the most seamless way for Apple to do it, as the vast majority of people use only one email address and one password for everything. Only those of us who had the same email adress but different a different passwords for MobileMe and Apple ID will have noticed. Annoying for us few, but a clever strategy on Apple's part, becasue we have been driven to fix the issue ourselves by chaning the password, and in doing so we have realised that our mobileme account is now the same thing as our Apple ID.

  • String does not gets splitted with "|"

    String does not gets splitted with "|" ?
    String str="abc#def|ijh#klm";
    String[] pieces=str.split("|");
    System.out.println(pieces[0]);

    '|' has special meaning (OR) so you need
    String[] pieces=str.split("\\|");

  • I'm trying to write a formula to return a blank cell if the condition is met, and to show the numerical difference if not.  Here is what I've written:=IF((F35-F29)=0, " ", (F35-F29)). It is returning 0.00, not a blank cell.  Where is my error?

    I'm trying to write a formula to return a blank cell if the condition is met, and to show the numerical difference if not.  Here is what I've written:=IF((F35-F29)=0, " ", (F35-F29)). When the condition is met (i.e., the difference=0) it is returning 0.00, not a blank cell.  Where is my error?

    Without knowing what is in F35 and F29, I can only guess.  Your formula matches what you said but if F35 and/or F29 are the results of formulas and are decimal numbers (not integers), it is very possible that they are not exactly the same number even though you think they should be.  IEEE Floating Point math often has very very small errors so the answer is not exactly what you would get with a pencil and paper. Try one or both of these things:
    Format the IF cell as scientific. is that 0.0 exactly zero? I suspect it will be some very tiny number.
    Type the exact same number into F35 and F29 and see if your IF formula works as you expect.
    You might need to use ROUND on F35, F29 and/or in your IF formula to get rid of the tiny math errors.
    If you search the forum for floating point math or IEEE 754 you should find more than a few posts about Numbers and floating point math. Or you can read about IEEE 754 on Wikipedia.  It trips up a lot of people.
    Here is a common example.  B2 and C2 are from the formulas shown in B1 and C1. They should both be exactly zero, if done with paper and pencil.  Neither is exactly zero (though I have them formatted with 2 decimals so they appear to be 0.00), they are different from each other, and subtracting one from the other is also not exactly zero.

  • My wifes iphone will not allow her to download from the app store when not connected to the computer. Does anyone know what is wrong?

    My wifes iphone will not allow her to download from the app store when not connected to the computer. Does anyone know what is wrong?

    Resetting your Mac's PRAM and NVRAM
    If you have Apple Care you should give them a call.

  • HT201363 I need to reset a Iphone4 I brought second hand, but the original owner do not know her apple Id or password. What should I do? (need help ASAP)

    I need to reset a Iphone4 I brought second hand, but the original owner do not know her apple Id or password. What should I do? (need help ASAP)

    You need to contact Apple. Click here, phone them, and ask for the Account Security team, or fill out and submit this form.
    (92501)

  • Not catching mobile network what to do? Reset network settings made no sim card in working condition box long lost what to do?

    not catching mobile network what to do? Reset network settings made no sim card in working condition  box long lost what to do?
    <Edited by Host>

    Contact your carrier and don't post personal information on a public user forum!

  • My daughter can not  remember her ipod password and it has been disabled, what can I do

    My daughter put in a new password and  can not remember it.  She has tried multiple times to log back in but now it states it is disabled and to go to itunes.  Any suggestions to how to open her ipod?  She does not have her own itunes account and uses mine and my husbands.. will this be an issue

    Place the iOS device in Recovery Mode and then connect to your computer and restore via iTunes. The iPod will be erased.
    iOS: Wrong passcode results in red disabled screen                          
    If recovery mode does not work try DFU mode.                         
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings         

  • Help with Oracle Connection- "Input string was not in a correct format"

    Hello, can some one, anyone please help me. I have a simple VS 2005 C# application that connects to oracle. I've set it up to take the username, password and tnsname as arguments. I am using Client 9i, version 9.2.0.401 of Oracle.DataAccess.dll, and .NET Framework 2.0.
    It works fine when I run it from VS 2005, I have also set up a test machine w/o VS 2005 and ran my install package and it runs fine. I sent it to one of my co-workers and when he tries it the OracleConnection obect fails with the error.
    "Input string was not in a correct format"
    strange in that it is not an ORA error, just the identifed text!?
    Here is the code:
    ## begin code
    OracleConnection dbc = new OracleConnection();
    string sConnectString = "User Id=" + username.ToString() + ";Password=" + password.ToString() + ";Data Source=" + tnsname.ToString();
    dbc.ConnectionString = sConnectString.ToString();
    MessageBox.Show("Attempting to Connect to Oracle");
    dbc.Open();
    MessageBox.Show("Connected to Oracle: " + dbc.ServerVersion);
    ## end code
    Pretty basic, what could be going on?
    Since this only happens with an installation, I put in the message boxes to verify exactly where it chokes. I get the first message box, then an error with the identified text. I've seen a number of posts regarding input string format problems, but not a one dealing with OracleConnection.Open(). I added all the ToString() calls just to make sure everything was a string but it did not change the end result.
    Anyone? Thanks In advance!
    Eric S.

    Hello,
    well, i got a message "...string not wellformed format...", too.
    If you have defined the parameters as string, you don't need the additonal "ToString()". Please ckeck your tnsnames -string. Try to debug this. I believe you have copy the format from the tnsnames.ora and there you have much brackets.
    For example, two code snippets:
    As datasource i use <Server>:<Port>/<Instance>
    try
    string FDsn ="User Id="+FDbUser+";Password="+FDbPwd;
    FDsn +=";Data Source=wth5:1521/Ora9.wth5";
    FConn = new OracleConnection(FDsn);
    FConn.Open();
    if (FConn.State == ConnectionState.Open )
         FConn.Close();
    catch (Exception ex)
         FStateMsg = "Connection to database failed. Check Configuration in parameter: ConnectionString. " + ex.Message;
    Above i connect to a Ora 9.2.0.1
    by using
    FDsn +=";Data Source=wth5:1522/XE";
    i connect to an OraExpress database on the same machine.
    My Oracle.dataAccess.dll ist the newest, 10.2.... and it runs under Framework 1.1.x and Framework 2.x
    I'll hope it will help you. Best regards!

  • ScheduleAtFixedRate - not catching interupt from FutureTask.cancel()

    I'm not quite understanding how to correctly cancel a thread that is spawned with scheduleAtFixedRate.
    main() schedules the MyTask runnable to run every second (which works fine). The runnable (MyTask) prints that its running every second. main() waits 5 seconds then calls cancel (implemented by FutureTask). This is where I get confused. cancel() (if called with a true flag) is supposed to interrupt the thread, but I never get a print in my catch for an InterruptException, and I never fall into my Thread.interupted() condition.
    So I have 3 questions:
    1. When I run this code from eclipse, the runnable does stop running (I stop getting the prints). So it does seem to be getting canceled. However, I don't understand why I'm not catching the thread interrupt.
    2. I'm forced to use the application terminate button in Eclipse to stop execution (not sure why it doesn't terminate normally).
    3. Whats the advantage of scheduleAtFixedRate over just spawning the thread with a while(shutdownFlag==true) loop (with a sleep at the end of the loop) and using a volatile atomic boolean to set the flag to false and have the thread terminate?
    Thanks for any help!
         public static void main(String[] args) {
              final int THREAD_POOL_SIZE = 1;
              final int PERIODIC_TIME = 1;
              final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(THREAD_POOL_SIZE);
              MyTaskSingleton myTask = MyTaskSingleton.getInstance();          
              try {
                      final ScheduledFuture<?> myTaskHandle =
                                  scheduler.scheduleAtFixedRate(myTask, 0, PERIODIC_TIME, TimeUnit.SECONDS);
                   Thread.sleep(5000);
                   System.out.println("TaskExecutor: MyTask cancel: " + myTaskHandle.cancel(true));
                   Thread.sleep(1000);
                   System.out.println("TaskExecutor: MyTask is done: " + myTaskHandle.isDone());
              } catch (InterruptedException e) {
                   System.out.println("TaskExecutor: caught exception");
                   e.printStackTrace();
         }Here is the run method of my runnable class.
    public void run() {
              try {
                   if (Thread.interrupted()){
                        System.out.println("MyTask: detected thread interrupt");                    
                        throw new InterruptedException();
                   System.out.println("MyTask: running...");
              catch(InterruptedException e){
                   System.out.println("MyTask: caught Interrupt Exception");
                   e.printStackTrace();
         }

    1. the only way your runnable will see an interrupted exception, is if it happens to be running when the cancel method is called. however, seeing as your run method is so trivial, the chances of the cancellation happening at the exact right time are very low. add a call to Thread.sleep() in your run method and you have a way better chance of seeing the interruption in the run method.
    2. you need to shutdown the executor at the end of the main method. the thread it is using is keeping the application from exiting.
    3. because you don't have to write all the code your self. not to mention that you can use 1 thread for multiple scheduled tasks (if you need more than 1).

  • Java.lang.string(split)

    I am trying to split a delimited input record using the Perl equivalent pattern of /\|/. Can someone tell me what that translates too exactly in Java? My guess is "//'\'|//".
    Also once I split to an array I would like to pull the contents of each field out individually. The string.split function appears to place the entire record in the array. I am using the following syntax with
    the bufferedReader:
    String[] RecFields = thisLine.split("//'\'|//");
    My understanding was that this would place each field in it's own Array element without saving the delimeter. So that I could retrieve field
    number 3 in it's entirety for example by using the syntax:
    String strField3 = RecFields[3];
    StringTokenizer has already been tried and will not work because of null (empty) values in the string are skipped as Array elements.

    That was it!!! It was the actual delimiter string. I thought the extra slashes were an "OR" statement to eliminate duplicate records. I'll have to get this confirmed with Perl though. It's working perfectly now with \\| as the delimiter string. For those of you who are curious it was a 20 field pipe delimited record. Each field hada a variable length. The only records with values in each field all the time were fields 1 & 2, the others can contain null values. However all 20 fields are delimited no matter what value they contain.
    Thanks for your help everyone!

  • 'My Application Page' is not allowed here because it does not extend class 'System.Web.UI.Page'

    I have a custom SharePoint 2010 solution that includes an aspx page. The aspx page in is in the /layouts folder within the solution and I created it by just adding an application page to the solution. I am trying to create a parent-child relationship between
    two different lists in SharePoint. From the parent I have a custom button on the ribbon that creates a child item with the ID of the parent stamped on it.
    The page is just a processing page that forwards on parameters from the parent to the new child item. (i.e. the ID value)
    The code generated when I add the aspx page is below:
    <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
    <%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
    <%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
    <%@ Import Namespace="Microsoft.SharePoint" %>
    <%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="processingpage.aspx.cs" Inherits="MY.Solution.Layouts.MY.Solution.processingpage" MasterPageFile="~/_layouts/application.master" %>
    <asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    </asp:Content>
    <asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    </asp:Content>
    <asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server"> Processing Page </asp:Content>
    <asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" > Processing Page </asp:Content>
    The code behind is as follows:
    using System;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration;
    using Microsoft.SharePoint.WebControls;
    using Microsoft.SharePoint.Utilities;
    using System.Reflection;
    namespace MY.Solution.Layouts.MY.Solution
    public partial class processingpage : LayoutsPageBase
    protected void Page_Load(object sender, EventArgs e)
    try
    //Get a reference to the SPWeb object
    SPWeb oWeb = SPContext.Current.Web;
    //Use the Parameters That Are Passed In
    SPList thisList = oWeb.Lists[new Guid(Request.QueryString["List"])];
    SPListItem thisItem = thisList.GetItemById(int.Parse(Request.QueryString["ID"]));
    sContentType = thisItem["ContentType"].ToString();
    sContentTypeID = thisItem.ContentTypeId.ToString();
    if (sContentType == "Some Content Type")
    sContentTypeID = "";
    sAIID = thisItem["ID"].ToString();
    //Redirect to newform.aspx with the Appropriate parameters.
    Context.Response.Redirect(oWeb.Url + "/Lists/Blist" + "/NewForm.aspx?AIID=" + sAIAuditID.ToString() + "&ContentTypeId=" + sContentTypeID + "&ParentItemID" + Context.Request["ID"]);
    else if (sContentType == "Some Content Type")
    sContentTypeID = "";
    sAIID = thisItem["AIID"].ToString();
    //Redirect to newform.aspx with the Appropriate parameters.
    Context.Response.Redirect(oWeb.Url + "/Lists/AList" + "/NewForm.aspx?AIID=" + sAIID.ToString() + "&ContentTypeId=" + sContentTypeID + "&ParentItemID" + Context.Request["ID"]);
    else if (sContentType == "Some Content Type")
    sContentTypeID = "";
    sAICID = thisItem["AICID"].ToString();
    //Redirect to newform.aspx with the Appropriate parameters.
    Context.Response.Redirect(oWeb.Url + "/Lists/CList" + "/NewForm.aspx?AICID=" + sAICID.ToString() + "&ContentTypeId=" + sContentTypeID + "&ParentItemID" + Context.Request["ID"]);
    else
    LoggingService.LogError("MY.Solution - Processing Page", "No Applicable Content Type Found.");
    catch (Exception ex)
    LoggingService.LogError("My.Solution - Processing Page", ex.Message);
    finally
    //DO SOME FINAL THINGS HERE WHEN REQUIRED.
    In the page I need to use Request.QueryString to get the values from the URL. But when I deploy the solution and load the page I get the error:
    'MY.Solution.Layouts.MY.Solution.processingpage' is not allowed here because it does not extend class 'System.Web.UI.Page'.
    When I change the line:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="processingpage.aspx.cs" Inherits="MY.Solution.Layouts.MY.Solution.processingpage" MasterPageFile="~/_layouts/application.master" %>
    to inherit as follows:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="processingpage.aspx.cs" Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" MasterPageFile="~/_layouts/application.master" %>
    it does not work either.
    If I change it to inherit like below:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="processingpage.aspx.cs" Inherits="System.Web.UI.Page" MasterPageFile="~/_layouts/application.master" %>
    it also does not work.
    What does this error actually mean?  And why doesn't the default code generated by Visual Studio work?

    @NadeemYousuf I have tried this too and it didn't work.  
    What does the error even mean?  And why does the error appear with default Visual Studio code?  In my example I have just added a basic application page with no other code in it and it still does not work.

Maybe you are looking for