using replace() in a text file for changing words - not char sequences

edited November 2015 in Programming Questions

i have a text file. I want to change some words. I thought it was easy to do using replace(). Which works but too much, i mean that it changes all occurences of char sequence, and sometimes changes words sometimes changes only char sequence into a word. In order to be much clear see the example (i want to change only the word "pur")===

String s;

void setup(){
    size(400,200);
    background(0);
    fill(255);
    textSize(24);

    s= "pur pureté purify";
    String dep = "pur";
    s = s.replace(dep, "kleen"); 
    text(s, 100,100);
    ///displays: kleen kleeneté, kleenify.....
}

Solution (as for me!!!) could be to test wether next char is ' ' but i don't see how to do that in a simple way, knowing that the the real text file is 100 pages long. Another one to write String dep = "pur " instead of "pur", but with the real text this changes the whole textAlign, + it works only if the word is the first one. Another solution:: to make an arrayList, then get && remove the old word, then add the new one, then transform my array in a string.... and it probably works but seems really stupid!!!

Any idea??? thanks in advance

Tagged:

Answers

  • you can use regular expressions for such tasks. In your case this could be something like this:

    String original= "pur pureté pur. purify pur, purify.";
    String expression = "pur([:;., ])";
    String out = original.replaceAll(expression, "kleen$1");
    
    println(out);
    

    that would replace all occurences of "pur" that are followed by a space or one of these chracters: :;.,.

  • and

    ? ! ) ] } 
    
  • Answer ✓

    I forgot about \b
    You can search for word-boundaries directly like this:

    String expression = "\\bpur\\b";

    The first example was wrong anyways, because it would still affect words like "impur".

  • @benja::: your second answer works:: looking for word-boundaries...Thanks!

Sign In or Register to comment.