Results 1 to 3 of 3
  1. #1
    Cyrus is offline Member
    Join Date
    Mar 2014
    Posts
    18
    Rep Power
    0

    Default Java regular expressions, simple search and replace

    I want to do a simple search and replace regular expression of lines. I am very unfamilar with Java regular expressions, and I'm not sure how to do something as simple as what I want to do.

    I have lines that look like this...
    Java Code:
    access_log /home/%USER%/access_log

    I want them changed so %USER% changes to a string, such as "cyrus," so they appear like this
    Java Code:
    access_log /home/cyrus/access_log
    The reason I want to use regular expressions is because I want to use the replaceAll method of the java.lang.String object. If I use replace I have to convert my strings into char arrays, and my code becomes bulky.

  2. #2
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: Java regular expressions, simple search and replace

    You can specify %USER% directly without using regular expression constructs:

    Java Code:
    String origString = "access_log /home/%USER%/access_log";
    String replacedStr = origString.replaceAll("%USER%", "cyrus");
    Note that if you'd rather not work with regular expressions, you can also use StringBuilder's replace method, e.g.,

    Java Code:
    StringBuilder builder = new StringBuilder(origString);
    int startPercentIndex = origString.indexOf('%');
    builder.replace(startPercentIndex, startPercentIndex + "%USER%".length(), "cyrus");
    See StringBuilder (Java Platform SE 7 ).

  3. #3
    Cyrus is offline Member
    Join Date
    Mar 2014
    Posts
    18
    Rep Power
    0

    Default Re: Java regular expressions, simple search and replace

    Thanks, that has been helpful.

Similar Threads

  1. java regular expressions
    By alexandra12 in forum New To Java
    Replies: 4
    Last Post: 08-28-2013, 01:09 PM
  2. Java and regular expressions
    By kosmos890 in forum New To Java
    Replies: 3
    Last Post: 01-18-2013, 03:57 PM
  3. Replies: 0
    Last Post: 06-26-2012, 10:19 AM
  4. Using regular expressions for search
    By carderne in forum New To Java
    Replies: 9
    Last Post: 05-24-2009, 04:58 AM
  5. Replies: 0
    Last Post: 04-16-2008, 10:59 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •