Regular Expression - uppercase the first letter.

I'm trying to process a String so that sentences without a starting capital letter have that letter made uppercase. The code I have so far is:
import java.util.regex.*;
public class TestRegexp{
     public static void main(String[] args){
          String myString = new String("Hello. capital");
          // TODO: Fix this so that it does uppercase the first letter
          String pattern = new String("\\.\\s+\\w");
          Pattern r = Pattern.compile(pattern);
          Matcher n = r.matcher(newString);
          String newString = n.replaceAll("\\. " + "\\w".toUpperCase());
          System.out.println(newString);
I want the output to be:
Hello. Capital
But this doesn't work. Is there a way to do this using the java.util.regex library and thus avoiding the StringTokeniser route?
Thanks.

The regex package doesn't provide a direct way to do what you want, but you can manage it by using some lower-level methods of the Matcher class:
Public String capitalizeSentences(String str)
  Pattern p = Pattern.compile("(\\.\\s+)(\\w)");
  Matcher m = p.matcher(str);
  StringBuffer sb = new StringBuffer();
  while (m.find())
    m.appendReplacement(sb, "$1");
    sb.append(m.group(2).toUpperCase());
  m.appendTail(sb);
  return sb.toString();
}

Similar Messages

  • Uppercase the first letter in a selectedtext() in a jtextfield

    Hello,
    I want to uppercase the first letter of the selected text in a jtexfield.
    I tried :
    StringBuffer stb = new StringBuffer(textField.getSelectedText());
    stb.setCharAt(0, Character.toUpperCase(stb.charAt(0)));
    but it doesn't work
    can anyone help me ?
    thanx in advance

    Well that function shows some bugs then I replace it with this one usins the text area reaplace slected text as camickr said (thanx camickr) and the position of the cursor.
    here is the new function :
       * Capitalize the first letter of a selectd string
       * but leave the rest as they are.
      public void capitalizeFirstLetter() {
        //get selected text
        selectedText = textArea.getSelectedText();
        try {
          //String buffer to change the case of a letter in a given index
          StringBuffer stb = new StringBuffer(selectedText);
          //Capitalize the first letter of the selected text
          stb.setCharAt(0, Character.toUpperCase(selectedText.charAt(0)));
          //Repalce the selected text with the same but with first letter capitlized
          textArea.replaceSelection(stb.toString());
          tableModel.setValueAt(stb.toString(),
                                sorter.modelIndex(this.getSelectedRow()),
                                findColumnIndex());
          //Renew Selection
          textArea.setSelectionStart(textArea.getCaretPosition() -
                                     selectedText.length());
          textArea.setSelectionEnd(textArea.getCaretPosition());
        catch (Exception ex) {
          JOptionPane.showMessageDialog(null,
                                        "No Selection found, plese select some text before apply this",
                                        JOptionPane.WARNING_MESSAGE);
      }

  • My ipad keypad make a loud snap noise when I start to type. It's not the regular click sound it sounds like an electric snap and it just started to happen. It only snaps when I type the first letter

    My ipad keypad makes a loud snap noise when I start to type. It's not the regular click sound it sounds like an electric snap and it just started to happen. It only snaps when I type the first letter
    Ipad only about 2 months old. 64gb cellular
    Has anyone had this problem?

    in the future, buy this, this is what the Pros use:
    for drops, accidents, spills, loss, or theft, purchase a TYPE of insurance called "inland marine insurance"
    roughly $30 per year for a device(s) with 0 deductible, used same for over 20 years, same insurance the pros use on their portable devices.
    very cheap, very useful insurance, most people dont know about same.
    http://en.wikipedia.org/wiki/Inland_marine_insurance

  • How do you change the first letter of a new line from uppercase to lowercase?

    In filling in case sensitive id's and passwords, the iPad automatically capitalizes the first letter---how do you change to lower case?

    You can shut off Auto Capitalization in the settings to prevent that from happening.  Go to Settings>General>Keyboard>Auto Capitalization>Off.
    You can change to lower case manually by tapping the "black X icon in the arrow" in the upper right corner of the keyboard to delete the capital letter and then type in the lower case letter.

  • Chunk expressions: Need the first and last char position from member.word[x]?

    I need to build a linear list of the string positions of the
    first and last character of each word in a string. For example if I
    have the string myPet = “DOG CAT FISH” then myList =
    [[1,3],[5,7],[9,12]]
    myPet.word[x] will let me access the individual words but
    I’m not sure how to get the char position of the beginning
    and end of each. Please help, it’s Friday and my brain has
    left for the weekend.

    Touche, Sean.
    "Sean Wilson" <[email protected]> wrote in
    message
    news:fqa8ap$bga$[email protected]..
    > Hi Craig,
    >
    > Your's fails if any word is repeated. Try it with "DOG
    CAT FISH DOG"
    >
    > This one seems to work, although there are probably more
    efficient ways to
    > go about it. A regular expression and the PRegEx xtra
    would certainly be
    > quicker, especially as the string gets longer
    >
    > on mGetWordBoundaries aString
    > -- basic error check
    > if stringP(aString) = 0 then return []
    > if length(aString) = 0 then return []
    >
    > lWhitespace = [SPACE, TAB, RETURN, numToChar(10)]
    > tStart = 1
    > tChar = aString.char[tStart]
    > repeat while lWhitespace.getPos(tChar)
    > tStart = tStart + 1
    > tChar = aString.char[tStart]
    > end repeat
    >
    > lPositions = []
    > repeat with w = 1 to aString.word.count
    > tEnd = tStart + aString.word[w].char.count - 1
    > lPositions.append([tStart, tEnd])
    > tStart = tEnd + 1
    > tChar = aString.char[tStart]
    > repeat while lWhitespace.getPos(tChar)
    > tStart = tStart + 1
    > tChar = aString.char[tStart]
    > end repeat
    > end repeat
    > return lPositions
    > end

  • Create a customer code using the First letter of a customer name and the last 4 digits of a phone number

    I am trying to create a form where one the customer has input their name and phone number it should grab the first letter of the customer's name and then the last 4 digits of the phone number.
    I am not very good at coding, and have VERY VERY limited background in coding. I understand a little (the basics pretty much).
    I am thinking i am not using the right expression to get what i want. Below is the statement I have write. This is just to find the first letter of the name, have an idea on how to get the phone number but i was trying the use the "left" and "right" functions but they wouldn't work. More specifically the left.
    form1.#subform[0].CustCode::initialize - (JavaScript, client)
    str = CustName;
    var a = str.substr(0, 1);
    any help would be greatly appreciated.
    If more information is needed, please don't hesitate to ask.

    If you switch your language to FormCalc you can use the Left and Right functions, e.g.
    Concat(Left(Name,1) , Right(Phone,4))

  • Making the first letter of every word a capital

    hello CF oracles
    could you guys please advise me the best way to make the
    first letter in every word of a string a capital letter. (and make
    all the other letters lower case).
    eg. convert "the quick brown fox" into "The Quick Brown Fox"
    or convert "THE QUICK BROWN FOX" into "The Quick Brown Fox"
    I am taking form data and inserting it into my table, so i
    want to get it right as the data is inserted.
    i found a "UDF" on CFLIb.org that proports to do this, but i
    don't know how to set up a UDF, are there other ways or is this
    considered the best approach.
    http://www.cflib.org/udf.cfm?id=9&enable=1
    thanks for any help you can give me

    found it, here's the top info, Titlecase is what you want for
    this.:
    changecase.cfm
    Rev 1.01
    cf_changecase is a simple custom tag to format case in given
    string.
    (c) 2001, Rizal Firmansyah, [email protected]
    Input var:
    * case (mandatory)
    possible inputs are
    - sentencecase: Sentence case (default)
    - titlecase: Title Case
    - lowercase: lowercase
    - uppercase: UPPER CASE
    "happysailingdude" <[email protected]> wrote
    in message
    news:e46tjv$e30$[email protected]..
    > hi Dan thanks very much. I have made an executive
    decision to do a bit of
    > a
    > hack for now as my site is only small so if a user
    enters something in the
    > wrong way i can quickly manually update it myself.
    >
    > so now i have this which works 9 times out of ten if the
    user enters a one
    > word name eg "bill" or "fred" of "jane" then it works
    just fine
    >
    > the only time it doesnt work is if the user's name is
    more than 1 word (or
    > is
    > hyphenated) eg "mary anne" or "anne-marie" hence the
    first cfif line - in
    > these
    > cases i can manually update
    >
    > i put this here in case it is of use to anyone else
    >
    > cheers
    >
    > <cfif not (FORM.firstName contains " " or
    FORM.firstname contains "-")>
    > '#Left( UCase( "#FORM.firstName#" ), 1 )##Right( LCase(
    > "#FORM.firstName#" ), Len("#FORM.firstName#" ) - 1 )#'
    > <cfelse>
    > '#FORM.firstName#'
    > </cfif>
    >

  • How to Capitalize the first letter in a text field?

    I have a text field of first_name and one of last_name.  I want to make sure not matter what format the user inputs the the first letter is Capitalized and the rest is lower case.  Can someone tell me how this is done?  Thanks!

    Rick4209 wrote:
    I have a text field of first_name and one of last_name.  I want to make sure not matter what format the user inputs the the first letter is Capitalized and the rest is lower case.  Can someone tell me how this is done?  Thanks!
    It depends on what you want to do with the name. If this is for inserting the name in a database and you're using PHP, it's very simple:
    $name = 'DaVID';
    $formatted = ucfirst(strtolower($name));
    echo $formatted; // outputs 'David'
    This nests two functions: the inner function, strtolower(), converts everything to lowercase, and the outer function, ucfirst(), converts the first letter to uppercase.

  • I have version 3.6.16 and when I login to my hotmail account, and type the first letter of the email address, a drop down box appears with my hotmail address and I can choose it from that box with a click. How do I get version 4 to do this? Thanks.

    I have version 3.6.16 and when I login to my hotmail account, and type the first letter of the email address, a drop down box appears with my hotmail address and I can choose it from that box with a click.
    How do I get version 4 to do this?
    Thanks.

    The new but not-ready-for-prime-time autocomplete method searches for matches that contain the entered text, not just ones that begin with the string. Your options are:
    1) type in longer strings that narrow the search
    2) use an add-on to search just the beginnings:
    https://support.mozilla.org/en-US/questions/1037469
    3) install an older version of TB:
    http://ftp.mozilla.org/pub/mozilla.org/thunderbird/releases/

  • I "reply"ed to an e-mail message. The next time when I chose to write a new message and type the first letter of the person I replied to earlier, that name and e-mail address appears as a choice included in a pop up list of my contacts.

    I "reply"ed to an e-mail message. The next time when I chose to write a new message and type the first letter of the person I replied to earlier, that name and e-mail address appears as a choice included in a pop up list of my contacts. The persons name is not in my contacts and I would like to delete it from popping up. Do you know how I can do this?

    The Mail app on the iPad/iPhone/iPod Touch does have an option to clear previous recipients. You can learn to live with it.  But if you want to get rid of it, the only way to remove these cached email addresses from the Mail application is restoring the iPhone/iPod Touch as a new phone/iPod.  If you restore from backup, the cache is also restored.
    This article shows you the screens you will see during the restore:  http://support.apple.com/kb/HT1414

  • How do I delete an email address from the dropdown that appears after I type the first letter of the recipiants address in the To: bar.

    When I open compose and type the first letter of the recipients address in the To: bar a dropdown appears with a listing of the email addresses I have sent messages to in the past as well as addresses of my contacts list.
    How do I delete an address from this dropdown?

    Start Firefox in <u>[[Safe Mode]]</u> to check if one of the extensions or if hardware acceleration is causing the problem (switch to the DEFAULT theme: Firefox (Tools) > Add-ons > Appearance/Themes).
    *Don't make any changes on the Safe mode start window.
    *https://support.mozilla.com/kb/Safe+Mode

  • How to Capitalize the first letter or an entire word using a shortcut on the keyboard just like in microsoft that uses shift+F3

    please how can one How to Capitalize the first letter or an entire word using a shortcut on the keyboard just like in microsoft that uses shift+F3

    What do you mean there was "no effect?" I'm not aware of any effects.
    It looks like that Service is also in the App Store. From their screen shots, the services are prefaced with WordService:
    You can see an example in the App Store for their app: App Store
    After installing, you should now have those text services in your Services menu. You can then add shortcuts in the Keyboard System Prefs.
    Most Apple apps have a Transformations menu in the Edit menu. You can Make upper, lower, and Initial caps with those. I would stick with Word Services, but you can make Application Shortcuts for the items in the Transformations menu.
    Again, in Keyboard System Prefs, Under Applications, Click the Add button on the right side pane.
    Set it for All Applications
    Enter the menu command exactly as they appear in the Transformation menu (separate entries for each),
    Make Upper Case
    Make Lower Case
    Capitalize
    Give them a shortcut.

  • I don't want the first letter of every line to be capitalized

    When I try to put in user id's and passwords on web sites, I don't always want the first letter to be capitalized.  How do you make the Ipad stop doing this?

    Settings -> General -> Keyboard
    Turn off Auto-Capitalization.
    Regards.

  • How to capitalize the first letter of each  word in a sentence?

    Can anyone please explain how to split a sentence at a comma, or space or hyphen in to words and capitalize the first letter of each word. But I don't know how many words the sentence contains.

    HI,
    data : begin of itab occurs 0,
             words(40),
             end of itab.
    data : v_sentence(1000).
    data : lv_firstchar.
    split v_sentence at ',' into table itab.
    loop at itab.
    translate itab-words+0(1) to upper case.
    modify itab index sy-tabix.
    endloop.

  • Getting the autocomplete setting to work by typing the first letter of a word

    Before I installed Firefox 5.0, I had made it so that whenever I visited a website that remembered an account/password of mine, this happened:
    1.- It asked for my master password.
    2.- After entering it, I would click on the form field and then type in the FIRST LETTER of the account.
    3.- When entering that exact first letter, Firefox would suggest in a drop-down menu the account or accounts that started with that letter on that particular site, e.g.: say I have a Twitter account that is "koko999". If I went to twitter.com and entered the letter "k" in the form field (after entering the master password), Firefox would suggest the account "koko999" in the drop-down menu.
    4.- After selecting the account that I desired from the drop-down menu, Firefox would automatically autocomplete the password.
    5.- Then, if I closed Firefox, all my active accounts would close/sign out. So, if afterwards I opened Firefox, I would have to repeat from Step 1 if I wanted to use an account, e.g.: if I closed FF while having my Twitter account logged in, and then opened FF again, I would have to start from Step 1.
    Now, I had this setting for a bunch of different websites. After installing Firefox 5.0, this configuration vanished or something. Now, when entering the master password, Firefox autocompletes EVERYTHING. Say, using the example from before, that I go to twitter.com. Firefox asks for the master password, I enter it and then the ID/password for the twitter account automatically fills in without me entering any letter in the form field. And I do not want Firefox to do that!
    So, I'm asking for help. I know that what I what to do is not impossible, I just can't find the way to do it! I kinda need the exact steps. Thanks a lot!

    See:
    * http://kb.mozillazine.org/Password_only_filled_after_entering_user_name
    * http://kb.mozillazine.org/signon.autofillForms (false)
    If you are in Private Browsing then Firefox wont fill the names and passwords automatically.
    You can set the pref <b>browser.sessionstore.privacy_level</b> to 2 (never) or 1 (non-HTTPS, default in Firefox 3 versions) on the <b>about:config</b> page to disable saving cookies via session restore.
    * http://kb.mozillazine.org/browser.sessionstore.privacy_level
    You can also use [[Clear Recent History]] to clear the "Active Logins" when you close Firefox.
    To open the <i>about:config</i> page, type <b>about:config</b> in the location (address) bar and press the "<i>Enter</i>" key, just like you type the url of a website to open a website.<br />
    If you see a warning then you can confirm that you want to access that page.<br />
    You can use the Filter bar at to top of the about:config page to locate a pref more easily.

Maybe you are looking for

  • How do i blend image and video on premier?

    Hello Everyone I'm trying to add a video onto an image on Premier. I want the image to be still and the video to play in the background. How do I make an image and video blend together in Premier? Any tips/effects to make this look more interesting?

  • Creating new apple id with old email address

    Our old G5 has crashed and burned, we just bought a new 27" Imac and are trying to register it but It's been so long that I dont remember the apple id. When I try to start from scratch and create a new id it keeps telling me the email address is alre

  • [SOLVED] Intel x3100 Laptop Video Card: which driver to use?

    I tried the xf86-video-intel package, but when I try to start X, it returns the "no screens found" error, with OR without a xorg.conf. Last edited by trusktr (2010-08-20 19:37:28)

  • So I have a 1st gen iPad, I can't get to download ios8 version to my pad

    HOw can I get iOS 8 on my first gen pad have the space. Just won't let me

  • Hpvpldrv09

    HI, I have a problem which seems to be unknown here. After installing a Officejet 8600 pro on an XP Pro SP3 maschine it is not possible to print or even look at the printer settings from other software. OO 3.3 crashes when printing and the document n