Regex in Richtextbox

I know how to use Regular expression but how i can Find a text in Richtextbox using regex?(to find and highlight text in RTB)
Thanks!

Ok, could you then explain in a bit more detail what you are looking for ?
Should it be highlighted while typing in the rtb or after it is typed , using a button ?
Which words should be highlighted, is it a big list, is it a fixed list etc ...
I wanted to create a HTML highlighter (fir highlighting tags and attributes)
Finally I succeeded
I have created a HTMLcodeHighlighter using web browser
I put two Webbrowser to form (1 for preview & 1 for codeview)
WB - Wcode
I have generated this code:
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Windows.Forms
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim Htm As String = "<html><body><font face='b lotus'></font></body></html>"
wcode.DocumentText = Htm
WB.DocumentText = Htm
While wcode.ReadyState <> WebBrowserReadyState.Complete
My.Application.DoEvents()
End While
wcode.Document.OpenNew(0)
wcode.Document.Write(Htm)
wcode.Document.DomDocument.designmode = "On"
End Sub
Private Sub ToolStripButton2_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton2.Click
If wcode.Document.Body IsNot Nothing Then
Dim tx As String = ""
tx = WB.DocumentText
tx = Regex.Replace(tx, "(?i-mxs)<[/\?]?.*?[\s>]", "#^$&*^")
tx = Regex.Replace(tx, "=.*?""?[\s>]", "#!$&*!")
tx = Regex.Replace(tx, "<.*?>", "#+$&*!")
tx = Regex.Replace(tx, "(?ims-){.*?}", "##$&*!")
tx = Regex.Replace(tx, """.+?""", "#%$&*%")
wcode.Document.Body.InnerText = tx
wcode.Document.Body.Style = "font-weight:bold; font-family:""Courier New"""
tx = wcode.DocumentText
tx = tx.Replace("#^", "<font color=#CC0066>").Replace("*^", "</font>")
tx = tx.Replace("#!", "<font color=teal>").Replace("*!", "</font>").Replace("#+", "<font color=blue>")
tx = tx.Replace("#%", "<font color=maroon>").Replace("*%", "</font>").Replace("##", "<font color=#0066CC>")
wcode.Document.OpenNew(0)
wcode.Document.Write(tx)
End If
End Sub
Private Sub ToolStripButton3_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton3.Click
Dim ofd As New OpenFileDialog With {.Filter = "WebPage|*.htm"}
Dim Fn As String
If ofd.ShowDialog = 1 Then
Fn = ofd.FileName
WB.Navigate(Fn)
End If
End Sub
End Class
It works as fast as possible(in shortest time).

Similar Messages

  • How can i AppendText to richTextBox only if the text is new(different) from the text that is already in the richTextBox ?

    Code
    public void ScrollNews()
    listsext.Ext(page);
    combindedString = string.Join(Environment.NewLine, ListsExtractions.myList);
    richTextBox1.SelectAll();
    richTextBox1.SelectionAlignment = HorizontalAlignment.Right;
    richTextBox1.AppendText(combindedString);
    scrollerText = string.Join(Environment.NewLine, ListsExtractions.myListWithoutLinks);
    scroller1.TextToScroll = scrollerText;
    if (NewsLevels.newsLevel && NewsLevels.shouldStart)
    UpdateTextControls();
    scroller1.Start();
    NewsLevels.shouldStart = false;
    if (NewsLevels.newsLevel == false && NewsLevels.shouldStart)
    UpdateTextControls();
    scroller1.Start();
    NewsLevels.shouldStart = false;
    string[] rlines = richTextBox1.Lines;
    richTextBox1.SelectionStart = 0;
    richTextBox1.SelectionLength = rlines[0].Length;
    richTextBox1.SelectionColor = Color.Red;
    richTextBox1.Select(rlines[0].Length, rlines[1].Length + 1);
    richTextBox1.SelectionColor = Color.Green;
    RedColorAlert1();
    if (lines == null)
    label5.Text = "0";
    else
    label5.Text = lines.Length.ToString();
    The line is:
    richTextBox1.AppendText(combindedString);
    I'm calling this method ScrollNews every X minutes with a timer.
    The way it is now it will AppendText all the time. But i want it to Add the combinededString only if the text in combindedString was different from the text that is already in the richTextBox. Somhow to keep all the time the last text and compare it and
    if there is a new text then appen it.

    public void Scroll()
    listsext.Ext(page);
    combindedString = string.Join(Environment.NewLine, ListsExtractions.myList);
    richTextBox1.SelectAll();
    StringBuilder sb = new StringBuilder();
    sb.Append(combindedString);
    richTextBox1.SelectionAlignment = HorizontalAlignment.Right;
    richTextBox1.AppendText(combindedString);
    The problem is that now it will keep adding to the richTextBox the content in combindedString over and over again. I need somehow to check each time if the content in combindedString already exist in the richTextBox if not meaning it's new content then AppendText
    it.
    If it's the same already exist do nothing don't add it.
    EDIT
    I write to a text file the content of the ombindedString variable .The first content the lines is the combindedString:
    המשטרה עצרה אמא ל2 ילדים קטנים שבעלה נעצר בחשד למעורבות בעלה בכריתת עצים
    15:03 דווח במקור בתאריך : 09.03.15 : שעה
    http://rotter.net/forum/scoops1/189935.shtml
    אדם החשוד בעבירת מין בקטינים נעצר לאחר שהתלונן על 2 שסוחטים אותו על רקע מעשיו
    14:50 דווח במקור בתאריך : 09.03.15 : שעה
    http://rotter.net/forum/scoops1/189932.shtml
    אינדונזיה: 5 הרוגים בקריסת האנגר בנמל תעופה
    14:44 דווח במקור בתאריך : 09.03.15 : שעה
    http://rotter.net/forum/scoops1/189930.shtml
    אום אל-פחם: מספר חשודים עוכבו בחשד למעורבות במימון טרור
    14:04 דווח במקור בתאריך : 09.03.15 : שעה
    http://rotter.net/forum/scoops1/189914.shtml
    אלמנתו של רפ''ק ג'דעאן אסעד, שנרצח בפיגוע הדריסה, ילדה בן
    13:05 דווח במקור בתאריך : 09.03.15 : שעה
    http://rotter.net/forum/scoops1/189884.shtml
    תנאי ליברמן לכניסה לממשלה עונש מוות למחבלים חובת חתימה על מסמך נאמנות
    12:39 דווח במקור בתאריך : 09.03.15 : שעה
    http://rotter.net/forum/scoops1/189868.shtml
    תלמיד תיכון מרחובות חשוד שהפעיל מעבדה ביתית לזיוף תעודות זהות ואישורי מחלה
    12:03 דווח במקור בתאריך : 09.03.15 : שעה
    http://rotter.net/forum/scoops1/189856.shtml
    הצביעות של רענן שקד: האשים את אמהות 3 החטופים ומגנה את חגי הוברמן
    11:43 דווח במקור בתאריך : 09.03.15 : שעה
    http://rotter.net/forum/scoops1/189848.shtml
    And this is a screenshot i couldnt copy the text of the richTextBox1.Text
    richTextBox1.Text content image
    co uld be that the format of the text in the combindedString and the richTextBox1.Text looks different so it think it's not exist ?
    Update:
    Not sure if it's important but the combindedString i'm adding the text to it from the variable ListExtractions.myList
    myList is List and i build this List like that:
    private void ListToStringList(List<string> myl)
    for (int i = 0; i < AllNews.Count; i++)
    myl.Add(AllNews[i].text);
    IFormatProvider provider = CultureInfo.InvariantCulture;
    DateTime myTime = DateTime.ParseExact(AllNews[i].original_time, "DyyMMddTHHmm", provider);
    string results = myTime.ToString("HH:mm דווח במקור בתאריך : dd.MM.yy : שעה");
    myl.Add(results);
    myl.Add(AllNews[i].link);
    myl.Add(Environment.NewLine);
    myListWithoutLinks.Add(AllNews[i].text);
    myListWithoutLinks.Add(results);
    myListWithoutLinks.Add(Environment.NewLine);
    for (int i = 0; i < myl.Count; i++)
    myl[i] = Regex.Replace(myl[i], @"\t|\n|\r", "");
    And use it:
    ListToStringList(myList);

  • Problems with String.split(regex)

    Hi! I'm reading from a text file. I do it like this: i read lines in a loop, then I split each line into words, and in a for loop I process ale words. Heres the code:
    BufferedReader reader = new BufferedReader(new FileReader(file));
    String line;
    while ((line = reader.readLine()) != null) {
        String[] tokens = line.split(delimiters);
        for (String key : tokens) {
    doSthToToken();
    reader.close();The problem is that if it reads an empty line, such as where is only an "\n", the tokens table has the length == 1, and it processes a string == "". I think the problem is that my regex delimiters is wrong:
    String delimiters = "\\p{Space}|\\p{Punct}";
    Could anybody tell me what to do?

    Ok, so what do you suggest?I suggest you don't worry about it.
    Or if you are worried then you need to test the two different solutions and do some timings yourself.
    And how do you know the regex lib is so slow and badly written?First of all slowness is all relative. If something takes 1 millisecond vs 4 milliseconds is the user going to notice? Of course not which is why you are wasting your time trying to optimize an equals() method.
    A general rule is that any code that is written to be extremely flexible will also be slower than any code that is written for a specific function. Regex are used for complex pattern matching. StringTokenizer was written specifically to split a string based on given delimiters. I must admit I haven't tested both in your exact scenario, but I have tested it in other simple scenarios which is where I got my number.
    By the way I was able to write my own "SimpleTokenizer" which was about 30% faster than the StringTokenizer because I was able to make some assumptions. For example I only allowed a single delimiter to be specified vs multiple delimiter handled by the StringTokenizer. Therefore my code could be very specific and efficient. Now think about the code for a complex Regex and how general it must be.

  • Can we eliminate " from a String using regEx?

    Hi,
    I have a process and we are calling an external web service.
    Within code, I am setting the response from web service(string) to bpm object and using the same object in jsp for presentation.
    For Ex.
    bpmObject.empName = response from web service.
    within the jsp, have a java script where in I am validating the value.
    var empNm= "<f:fieldValue att="bpmObject.empName" onlyValue="true"/>";
    It works fine but some times when response from web service is having '"' - double quote, it is giving error.
    For Ex. bpmObject.empName = FirstName "SecondName" then the javascript error occurs. how can we remove the double quote from this?
    Tried bpmObject.empName.replace(from : "\"", @to : " ") but it is still giving the same output FirstName "SecondName"
    It works fine when I test by using a String str = "FirstName\"SecondName\"".replace(from : "\"", @to : " ") is giving correct result i.e. FirstName SecondName
    Can RegEx help in this?
    Thanks

    I know its better to handle in jsp/javascript
    var empNm= "<f:fieldValue att="bpmObject.empName" onlyValue="true"/>";
    but the above line is giving javascript error always.
    how to handle the same in bpm fpr code?
    Edited by: Sreekant on Mar 3, 2011 1:44 AM

  • How to save the RichTextBox Content in Text file

    hI ,
    I NEED TO SAVE THE RichTextBox Content in text file ? 

    If this IS a LabVIEW question, here's an example of how to load a rich text file (to help if you don't know how to get a rich text in LabVIEW).
    If you have a Rich Text Box, you can use the invoke method "SaveFile" to match the function you linked to.

  • Regex find and replace

    I have inherited a boatload of code that I need to "tweak".
    Currently, it contains many hundreds of refrences to a 2d
    array and
    references constants that I want to change to function calls.
    i.e.
    v(Svc,FutWTMargin)
    I want that to be changed into:
    v(Svc,getcol("FutWTMargin"))
    Now the bit in quotes "FutWTMargin" has many variations, but
    the structure
    of the original 2d array references are all consistent - it's
    just that
    there are several hundred of them that I need to change.
    Can someone help out with a regex that can change the
    FutWTMargin part to
    getcol("FutWTMargin") regardless of what the FutWTMargin text
    might actually
    say?
    Note to self... must learn regex at some point!
    Cheers,
    Rob
    http://robgt.com/ [Tutorials and
    Extensions]
    Firebox stuff:
    http://robgt.com/firebox
    Skype stuff:
    http://robgt.com/skype
    Dell stuff:
    http://robgt.com/dell
    SatNav stuff:
    http://robgt.com/satnav

    Thanks Mick!
    Cheers,
    Rob
    http://robgt.com/ [Tutorials and
    Extensions]
    Firebox stuff:
    http://robgt.com/firebox
    Skype stuff:
    http://robgt.com/skype
    Dell stuff:
    http://robgt.com/dell
    SatNav stuff:
    http://robgt.com/satnav

  • Find Replace from Textfile with regex

    Hello.
    I'm wondering if anyone knows about an existing script that does a find/replace by list like the script "FindChangeByList.jsx" that comes with every InDesign installation.
    This consists of tow parts, the script itself with the functionality and a simple textfile where you have simple one-liners capable of find/replace with regex.
    the Textfile:
    //FindChangeList.txt
    //A support file for the InDesign CS4 JavaScript FindChangeByList.jsx
    //This data file is tab-delimited, with carriage returns separating records.
    //The format of each record in the file is:
    //findType<tab>findProperties<tab>changeProperties<tab>findChangeOptions<tab>description
    //Where:
    //<tab> is a tab character
    //findType is "text", "grep", or "glyph" (this sets the type of find/change operation to use).
    //findProperties is a properties record (as text) of the find preferences.
    //changeProperties is a properties record (as text) of the change preferences.
    //findChangeOptions is a properties record (as text) of the find/change options.
    //description is a description of the find/change operation
    //Very simple example:
    //text          {findWhat:"--"}          {changeTo:"^_"}          {includeFootnotes:true, includeMasterPages:true, includeHiddenLayers:true, wholeWord:false}          Find all double dashes and replace with an em dash.
    //More complex example:
    //text          {findWhat:"^9^9.^9^9"}          {appliedCharacterStyle:"price"}          {include footnotes:true, include master pages:true, include hidden layers:true, whole word:false}          Find $10.00 to $99.99 and apply the character style "price".
    //All InDesign search metacharacters are allowed in the "findWhat" and "changeTo" properties for findTextPreferences and changeTextPreferences.
    //If you enter backslashes in the findWhat property of the findGrepPreferences object, they must be "escaped"
    //as shown in the example below:
    //{findWhat:"\\s+"}
    grep          {findWhat:"  +"}          {changeTo:" "}          {includeFootnotes:true, includeMasterPages:true, includeHiddenLayers:true, wholeWord:false}          Find all double spaces and replace with single spaces.
    grep          {findWhat:"\r "}          {changeTo:"\r"}          {includeFootnotes:true, includeMasterPages:true, includeHiddenLayers:true, wholeWord:false}          Find all returns followed by a space And replace with single returns.
    grep          {findWhat:" \r"}          {changeTo:"\r"}          {includeFootnotes:true, includeMasterPages:true, includeHiddenLayers:true, wholeWord:false}          Find all returns followed by a space and replace with single returns.
    grep          {findWhat:"\t\t+"}          {changeTo:"\t"}          {includeFootnotes:true, includeMasterPages:true, includeHiddenLayers:true, wholeWord:false}          Find all double tab characters and replace with single tab characters.
    grep          {findWhat:"\r\t"}          {changeTo:"\r"}          {includeFootnotes:true, includeMasterPages:true, includeHiddenLayers:true, wholeWord:false}          Find all returns followed by a tab character and replace with single returns.
    grep          {findWhat:"\t\r"}          {changeTo:"\r"}          {includeFootnotes:true, includeMasterPages:true, includeHiddenLayers:true, wholeWord:false}          Find all returns followed by a tab character and replace with single returns.
    grep          {findWhat:"\r\r+"}          {changeTo:"\r"}          {includeFootnotes:true, includeMasterPages:true, includeHiddenLayers:true, wholeWord:false}          Find all double returns and replace with single returns.
    text          {findWhat:" - "}          {changeTo:"^="}          {includeFootnotes:true, includeMasterPages:true, includeHiddenLayers:true, wholeWord:false}          Find all space-dash-space and replace with an en dash.
    text          {findWhat:"--"}          {changeTo:"^_"}          {includeFootnotes:true, includeMasterPages:true, includeHiddenLayers:true, wholeWord:false}          Find all dash-dash and replace with an em dash.
    The script:
    //FindChangeByList.jsx
    //An InDesign CS5.5 JavaScript
    @@@BUILDINFO@@@ "FindChangeByList.jsx" 3.0.0 15 December 2009
    //Loads a series of tab-delimited strings from a text file, then performs a series
    //of find/change operations based on the strings read from the file.
    //The data file is tab-delimited, with carriage returns separating records.
    //The format of each record in the file is:
    //findType<tab>findProperties<tab>changeProperties<tab>findChangeOptions<tab>description
    //Where:
    //<tab> is a tab character
    //findType is "text", "grep", or "glyph" (this sets the type of find/change operation to use).
    //findProperties is a properties record (as text) of the find preferences.
    //changeProperties is a properties record (as text) of the change preferences.
    //findChangeOptions is a properties record (as text) of the find/change options.
    //description is a description of the find/change operation
    //Very simple example:
    //text          {findWhat:"--"}          {changeTo:"^_"}          {includeFootnotes:true, includeMasterPages:true, includeHiddenLayers:true, wholeWord:false}          Find all double dashes and replace with an em dash.
    //More complex example:
    //text          {findWhat:"^9^9.^9^9"}          {appliedCharacterStyle:"price"}          {include footnotes:true, include master pages:true, include hidden layers:true, whole word:false}          Find $10.00 to $99.99 and apply the character style "price".
    //All InDesign search metacharacters are allowed in the "findWhat" and "changeTo" properties for findTextPreferences and changeTextPreferences.
    //If you enter backslashes in the findWhat property of the findGrepPreferences object, they must be "escaped"
    //as shown in the example below:
    //{findWhat:"\\s+"}
    //For more on InDesign scripting, go to http://www.adobe.com/products/indesign/scripting/index.html
    //or visit the InDesign Scripting User to User forum at http://www.adobeforums.com
    main();
    function main(){
              var myObject;
              //Make certain that user interaction (display of dialogs, etc.) is turned on.
              app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;
              if(app.documents.length > 0){
                        if(app.selection.length > 0){
                                  switch(app.selection[0].constructor.name){
                                            case "InsertionPoint":
                                            case "Character":
                                            case "Word":
                                            case "TextStyleRange":
                                            case "Line":
                                            case "Paragraph":
                                            case "TextColumn":
                                            case "Text":
                                            case "Cell":
                                            case "Column":
                                            case "Row":
                                            case "Table":
                                                      myDisplayDialog();
                                                      break;
                                            default:
                                                      //Something was selected, but it wasn't a text object, so search the document.
                                                      myFindChangeByList(app.documents.item(0));
                        else{
                                  //Nothing was selected, so simply search the document.
                                  myFindChangeByList(app.documents.item(0));
              else{
                        alert("No documents are open. Please open a document and try again.");
    function myDisplayDialog(){
              var myObject;
              var myDialog = app.dialogs.add({name:"FindChangeByList"});
              with(myDialog.dialogColumns.add()){
                        with(dialogRows.add()){
                                  with(dialogColumns.add()){
                                            staticTexts.add({staticLabel:"Search Range:"});
                                  var myRangeButtons = radiobuttonGroups.add();
                                  with(myRangeButtons){
                                            radiobuttonControls.add({staticLabel:"Document", checkedState:true});
                                            radiobuttonControls.add({staticLabel:"Selected Story"});
                                            if(app.selection[0].contents != ""){
                                                      radiobuttonControls.add({staticLabel:"Selection", checkedState:true});
              var myResult = myDialog.show();
              if(myResult == true){
                        switch(myRangeButtons.selectedButton){
                                  case 0:
                                            myObject = app.documents.item(0);
                                            break;
                                  case 1:
                                            myObject = app.selection[0].parentStory;
                                            break;
                                  case 2:
                                            myObject = app.selection[0];
                                            break;
                        myDialog.destroy();
                        myFindChangeByList(myObject);
              else{
                        myDialog.destroy();
    function myFindChangeByList(myObject){
              var myScriptFileName, myFindChangeFile, myFindChangeFileName, myScriptFile, myResult;
              var myFindChangeArray, myFindPreferences, myChangePreferences, myFindLimit, myStory;
              var myStartCharacter, myEndCharacter;
              var myFindChangeFile = myFindFile("/FindChangeSupport/FindChangeList.txt")
              if(myFindChangeFile != null){
                        myFindChangeFile = File(myFindChangeFile);
                        var myResult = myFindChangeFile.open("r", undefined, undefined);
                        if(myResult == true){
                                  //Loop through the find/change operations.
                                  do{
                                            myLine = myFindChangeFile.readln();
                                            //Ignore comment lines and blank lines.
                                            if((myLine.substring(0,4)=="text")||(myLine.substring(0,4)=="grep")|| (myLine.substring(0,5)=="glyph")){
                                                      myFindChangeArray = myLine.split("\t");
                                                      //The first field in the line is the findType string.
                                                      myFindType = myFindChangeArray[0];
                                                      //The second field in the line is the FindPreferences string.
                                                      myFindPreferences = myFindChangeArray[1];
                                                      //The second field in the line is the ChangePreferences string.
                                                      myChangePreferences = myFindChangeArray[2];
                                                      //The fourth field is the range--used only by text find/change.
                                                      myFindChangeOptions = myFindChangeArray[3];
                                                      switch(myFindType){
                                                                case "text":
                                                                          myFindText(myObject, myFindPreferences, myChangePreferences, myFindChangeOptions);
                                                                          break;
                                                                case "grep":
                                                                          myFindGrep(myObject, myFindPreferences, myChangePreferences, myFindChangeOptions);
                                                                          break;
                                                                case "glyph":
                                                                          myFindGlyph(myObject, myFindPreferences, myChangePreferences, myFindChangeOptions);
                                                                          break;
                                  } while(myFindChangeFile.eof == false);
                                  myFindChangeFile.close();
    function myFindText(myObject, myFindPreferences, myChangePreferences, myFindChangeOptions){
              //Reset the find/change preferences before each search.
              app.changeTextPreferences = NothingEnum.nothing;
              app.findTextPreferences = NothingEnum.nothing;
              var myString = "app.findTextPreferences.properties = "+ myFindPreferences + ";";
              myString += "app.changeTextPreferences.properties = " + myChangePreferences + ";";
              myString += "app.findChangeTextOptions.properties = " + myFindChangeOptions + ";";
              app.doScript(myString, ScriptLanguage.javascript);
              myFoundItems = myObject.changeText();
              //Reset the find/change preferences after each search.
              app.changeTextPreferences = NothingEnum.nothing;
              app.findTextPreferences = NothingEnum.nothing;
    function myFindGrep(myObject, myFindPreferences, myChangePreferences, myFindChangeOptions){
              //Reset the find/change grep preferences before each search.
              app.changeGrepPreferences = NothingEnum.nothing;
              app.findGrepPreferences = NothingEnum.nothing;
              var myString = "app.findGrepPreferences.properties = "+ myFindPreferences + ";";
              myString += "app.changeGrepPreferences.properties = " + myChangePreferences + ";";
              myString += "app.findChangeGrepOptions.properties = " + myFindChangeOptions + ";";
              app.doScript(myString, ScriptLanguage.javascript);
              var myFoundItems = myObject.changeGrep();
              //Reset the find/change grep preferences after each search.
              app.changeGrepPreferences = NothingEnum.nothing;
              app.findGrepPreferences = NothingEnum.nothing;
    function myFindGlyph(myObject, myFindPreferences, myChangePreferences, myFindChangeOptions){
              //Reset the find/change glyph preferences before each search.
              app.changeGlyphPreferences = NothingEnum.nothing;
              app.findGlyphPreferences = NothingEnum.nothing;
              var myString = "app.findGlyphPreferences.properties = "+ myFindPreferences + ";";
              myString += "app.changeGlyphPreferences.properties = " + myChangePreferences + ";";
              myString += "app.findChangeGlyphOptions.properties = " + myFindChangeOptions + ";";
              app.doScript(myString, ScriptLanguage.javascript);
              var myFoundItems = myObject.changeGlyph();
              //Reset the find/change glyph preferences after each search.
              app.changeGlyphPreferences = NothingEnum.nothing;
              app.findGlyphPreferences = NothingEnum.nothing;
    function myFindFile(myFilePath){
              var myScriptFile = myGetScriptPath();
              var myScriptFile = File(myScriptFile);
              var myScriptFolder = myScriptFile.path;
              myFilePath = myScriptFolder + myFilePath;
              if(File(myFilePath).exists == false){
                        //Display a dialog.
                        myFilePath = File.openDialog("Choose the file containing your find/change list");
              return myFilePath;
    function myGetScriptPath(){
              try{
                        myFile = app.activeScript;
              catch(myError){
                        myFile = myError.fileName;
              return myFile;
    This is a very useful and easy to maintain script which even people who cant write scripts (but know how to use regex) can do complex search replace mass replacements.
    Would love to find something like this for FrameMaker 12 (as i can't write scripts myself).
    regards
    daniel

    I have visited that site. The first item in the external link says: "You can also configure Firefox to automatically search for text when you type any characters outside of a text field. When typing in a text field these characters should show up in the text field and not trigger the Quick Find bar. "
    What I am looking for is the exact opposite. Once my first search is entered in the text box, and the info comes back, I want to start typing the next symbol, and have it automatically show up in the text box, not the Quick Find box. That is how it was working up until a couple of months ago.

  • Is there a way to put the cursor at a specific location in a RichTextBox?

    Is there a way to put the cursor at a specific location in a RichTextBox?
    The following code places the cursor at the start of a RichTextBox:
        RichTextBox RTbx
        RTbx.Focus();
        TextPointer tp = RTbx.CaretPosition;
        tp = tp.DocumentStart;
        RTbx.CaretPosition = tp;
    Not sure how to place it at a specific location other than start and end.
    The RichTextBox has contents.  At this point in the code, I do know the specific "word" in the contents, as well as the position (number of chars) where that word is located.  I just need to programmatically place the cursor at that location.
    bhs67

    Oh sorry, I see I missed something out my original reply.
    I have markup:
    <Grid>
    <RichTextBox Name="rtb">
    <FlowDocument>
    <Paragraph >This is the first paragraph</Paragraph>
    <Paragraph >TSecond paragraph is here</Paragraph>
    </FlowDocument>
    </RichTextBox>
    </Grid>
    Code - this is the window contentrendered event
    private void Window_ContentRendered(object sender, EventArgs e)
    rtb.Focus();
    // TextPointer moveTo = rtb.CaretPosition.GetNextInsertionPosition(LogicalDirection.Forward);
    TextPointer moveTo = rtb.CaretPosition.GetPositionAtOffset(9, LogicalDirection.Forward);
    if (moveTo != null)
    rtb.CaretPosition = moveTo;
    I see the cursor between the t and he of the second "the".
    Note that there are numerous other options such as the commented out line.
    Hope that helps.
    Recent Technet articles: Property List Editing;
    Dynamic XAML

  • How to check special characters in java code using Java.util.regex package

    String guid="first_Name;Last_Name";
    Pattern p5 = Pattern.compile("\\p{Punct}");
    Matcher m5 =p5.matcher(guid);
    boolean test=m5.matches();
    I want to find out the weather any speacial characters are there in the String guid using regex.
    but above code is always returning false. pls suggest.

    Pattern.compile ("[^\\w]");The above will match any non [a-zA-Z0-9_] character.
    Or you could do
    Pattern.compile("[^\\s^\\w]");This should match anything that is not a valid charcter and is not whitespace.

  • Is it possible to read and write to a file at the same time and display the results in a RichTextBox?

    Hi All,
    I have a purpose in winforms to have a "notepad like" editor that saves what ever i type to a file on the hard drive and reads from based. 
    So what i have is a tab with a richtextbox docked to fill. I would like to have that richtextbox read from a file on the hard drive, then save the changes i type when i either click off the tab or live if possible.
    I wills state that i am fairly new to the c# game and if this is possible and someone could post an example that would be awesome and totally appreciated.
    Thanks,
    jAC

    For those that are looking for the solution I went with here are the details
    Reading the file:
    // Wish List Section
    wishListRichTextBox.ResetText();
    string wlFolder = Application.StartupPath + "\\wishLists\\";
    string wlPath = wlFolder + selectedProduct + ".rtf";
    // Read from the text file and out put the results
    try
    { // create directory if it does not exist
    if (!Directory.Exists(wlFolder))
    Directory.CreateDirectory(wlFolder);
    } // create file if it does not exist
    if (!File.Exists(wlPath))
    File.Create(wlPath).Dispose();
    var iStream = new FileStream(wlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    var sr = new System.IO.StreamReader(iStream);
    var readData = sr.ReadToEnd();
    wishListRichTextBox.Text = readData;
    sr.Close();
    // If the read fails then output the error message in the same section
    catch (Exception ex)
    wishListRichTextBox.Text = "Error: " + ex.Message;
    Writing the file:
    private void wishlistTabChanged(object sender, EventArgs e)
    if(menuTabControl.SelectedTab != wishListTab){
    if (productComboBox.SelectedIndex >= 0)
    try
    string wlFolder = Application.StartupPath + "\\wishLists\\";
    string wlPath = wlFolder + productComboBox.SelectedItem + ".rtf";
    var oStream = new FileStream(wlPath, FileMode.Open, FileAccess.Write, FileShare.Read);
    oStream.SetLength(0);
    var sw = new System.IO.StreamWriter(oStream);
    sw.WriteLine(wishListRichTextBox.Text);
    sw.Close();
    catch (Exception ex)
    MessageBox.Show("Wish list for " + productComboBox.Text + " save failed. \n\nError: " +
    ex, "Wish List Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
    I mainly used Ammar.Zaied thought
    process on this. Thanks to everyone though, as you all pointed me in the right direction

  • Reading a String Literally - Finding the "\" Character with a Regex

    How do I search for "\" characters in a string? Such as..
    String text = "Temp\temp.txt";
    The problem is that Java will read "\t" as a tab, so that
    System.out.println(text);
    Will return
    Temp emp.txt
    Also, searching for the regex "\\\\" will return a null result, presumably because Java interprets the "\t" as a tab character, not as a literal "\" followed by a literal "t".
    How do I get Java to read the string without interpreting it?
    Thanks in advance

    Try also this:
    public static void main(String[] args) {
              String test1 = "String with a\\t which is not a tab but a t preceeded with a \\ character";
              String test2 = "String with a \t which is a tab";
              System.out.println("This are the Strings as user sees / enters them:");
              System.out.println(test1);
              System.out.println(test2);
              System.out.println("");
              System.out.println("***********************************************************");
              System.out.println("");
              System.out
                        .println("Splitting first string using a \\\\\\\\ regex which will be interpreted by the regex engine as \\\\ which will represent a \'\\\' character:");
              System.out.println("");
              for (String s : test1.split("\\\\")) {
                   System.out.println(s);
              System.out.println("");
              System.out.println("***********************************************************");
              System.out.println("");
              System.out.println("Splitting the second string just the same way:");
              System.out.println("");
              for (String s : test2.split("\\\\")) {
                   System.out.println(s);
         }and read the console output.
    It should be:
    This are the Strings as user sees / enters them:
    String with a\t which is not a tab but a t preceeded with a \ character
    String with a       which is a tab
    Splitting first string using a \\\\ regex which will be interpreted by the regex engine as \\ which will represent a '\' character:
    String with a
    t which is not a tab but a t preceeded with a
    character
    Splitting the second string just the same way:
    String with a       which is a tab

  • How to replace regex match into a char value (in the middle of a string)

    Hi uncle_alice and other great regex gurus
    One of my friends has a peculiar problem and I cant give him a solution.
    Using String#replaceAll(), i.e. NOT a Matcher loop, how could we convert matched digit string such as "65" into a char of its numeric value. That is, "65" should be converted into letter 'A'.
    Here's the failing code:
    public class GetChar{
      public static void main(String[] args){
        String orig = "this is an LF<#10#> and this is an 'A'<#65#>";
        String regx = "(<#)(\\d+)#>";
        //expected result : "this is an LF\n and this is an 'A'A"
        String result = orig.replaceAll(regx, "\\u00$2");
        // String result = orig.replaceAll(regx, "\\\\u00$2"); //this also doesn't work
        System.out.println(result);

    I don't know that we have lost anything substantial.i think its just that the kind of task this is
    especially useful for is kind of a blind-spot in the
    range of things java is a good-fit for (?)
    for certain tasks (eg process output munging) an
    experienced perl programmer could knock up (in perl)
    using built-in language features a couple of lines
    which in java could takes pages to do. If the cost is
    readability/maintainability/expandability etc.. then
    this might be a problem, but for a number of
    day-to-day tasks it isn't
    i'm trying to learn perl at the moment for this exact
    reason :)Yes. And when a Java source-code processor(a.k.a. compiler) sees the code like:
    line = line.replaceAll(regexp,  new String(new char[] {(char)(Integer.parseInt("$1"))}));or,
    line = line.replaceAll(regexp,  doMyProcessOn("$1")); //doMyProcess returns a Stringa common sense should have told him that "$1" isn't a literal string "$1" in this regular expression context.
    By the way, I abhor Perl code becaus of its incomprehensibleness. They can't be read by an average common sense. Java code can be, sort of ...

  • Java.util.regex error

    Hello,
    I checked JavaDoc multiple times but do not see what is wrong with
    myString.replaceAll("D:\\web\\mars","")which results in
    java.util.regex.PatternSyntaxException: Illegal/unsupported escape squence near index 7
    D:\web\mars
           ^
         at java.util.regex.Pattern.error(Unknown Source)
         at java.util.regex.Pattern.escape(Unknown Source)
         at java.util.regex.Pattern.atom(Unknown Source)
         at java.util.regex.Pattern.sequence(Unknown Source)
         at java.util.regex.Pattern.expr(Unknown Source)
         at java.util.regex.Pattern.compile(Unknown Source)
         at java.util.regex.Pattern.<init>(Unknown Source)
         at java.util.regex.Pattern.compile(Unknown Source)
         at java.lang.String.replaceAll(Unknown Source)
         at ArticleImageImportProcessor.main(ArticleImageImportProcessor.java:40)
    Exception in thread "main" please, every suggestion/hint is most appeciated

    You have to "encode" backslash twice, first for String purpose and second time because of special meaning of '\' in regular expressions.
    It should looks like
    myString.replaceAll("D:\\\\web\\\\mars","")

  • Simple Java regex question

    I have a file with set of Name:Value pairs
    e.g
    Action1:fail
    Action2:pass
    Action3:fred
    Using regex package I Want to get value of Name "Action1"
    I have tried diff things but I cannot figure out how I can do it. I can find Action1: is present or not but dont know how I can get value associated with it.
    I have tried:
    Pattern pattern = Pattern.compile("Action1");
    CharSequence charSequence = CharSequenceFromFile(fileName); // method retuning charsq from a file
    Matcher matcher = pattern.matcher(charSequence);
    if(matcher.find()){
         int start = matcher.end(0);
         System.out.println("matcher.group(0)"+ matcher.group(0));
    how I can get value associated with specific tag?
    thanks
    anmol

    read the data from the text file on a line basis and you can do:
    String line //get this somehow
    String[] keyPair = line.split(":")g
    System.out.println(keyPair[0]); //your name
    System.out.println(keyPair[1]); //your valueor if you've got the text file in one big string:
    String pattern = "(\\a*):(\\a*)$"; //{alpha}:{alpha}newline //?
    //then
    //do some things with match objects
    //look in the API at java.util.regex

  • RegEx: How to find out which part of the pattern failed?

    Hi there,
    I was wondering: is there any way to find out where the pattern matching failed?
    Say I got the string "John Paul Yoko Ringo", and I want to match it against the pattern /John Paul George Ringo/.
    I would like to know something like "pattern failed at index 11", or if I had groups something like "matching group 3 failed".
    Is there any way to do this? Thanks in advance!
    Best regards,
    - Torben

    jschell wrote:
    I would like to know something like "pattern failed at index 11", or if I had groups something like "matching group 3 failed".
    Is there any way to do this? Thanks in advance!
    I wonder if that is reasonable. It means that the parse tree for the regex would need to keep mapping information.
    At a minimum it is going to require an array, not a single result, because a regex can 'fail' in many ways.
    Consider the following regex with the following input
    /(a|b)d/
    abababababx
    Where does it 'fail'?Right. If you just want the character position at which it failed, those tools might tell you that as part of a bigger picture. But by itself, without any context, that number's not necessarily meaingful. A given character can be examined many times due to backtracking. Part of the expression could succeed for part of the input, then the expression might fail for the rest, so we backtrack, and may get several more failures, then more partial successes, all at different points, then ultimately it may fail anywhere within the input.
    So just knowing where isn't enough. You need to know what steps were taken to get there. I do think these tools provide that, though I haven't looked closely.

Maybe you are looking for

  • Add attachments using workflow api throwing error

    Hi, I am getting the following error when i am trying to add attachments using worklist API.      Missing class: invokeBPEL.MetaData      Dependent class: com.evermind.io.ClassLoaderObjectInputStream      Loader: oc4j:10.1.3      Code-Source: /D:/pro

  • Send Report output as attachment in excel

    Hi All, I am scheduling background Job for Auto mail of standard SAP report. I am able to send the details in html format, please guide me how to send report details in excel format. I have already check SCN but unable to find exact solution for same

  • BAPI_PO_CHANGE failing

    I am using BAPI_PO_CHANGE to add line item to the purchase order. This PO is taking reference from the SO of same company code. when i run this BAPI it gives me the following message: PO Changes Failed due to following reasons                  Changi

  • Memory leak with Swing application

    My application uses more and more memory as I use it. However, if it is working like I think, it is not creating more objects and has no reason to use more memory. When the application is minimized a lot of that memory is freed up. Does anyone know w

  • Problem when launching Photoshop CS3 in OSX 10.5.1 (Leopard)

    When I launch Photoshop CS3 it quits and a message comes: "can't launch Photoshop because file is locked. Go to 'File' > 'Get Info' and unlock the file". But the file is not locked. Any idea? Thanks.