Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Replace unless inside quotes?

  1. #1
    Join Date
    Feb 2013
    Thanked 0 Times in 0 Posts

    Default Replace unless inside quotes?

    Hey guys, sorry if this isn't the correct area for this.

    Basically, I am trying to write a method that will take a string, a target, and a replacement (a replacement function like string.replace). I want it to replace all instances of target with replacement EXCEPT for instances that occur within single or double quotes.

    Example input / output:

    this "Wont" be " replaced, be"

    call: replace(theString, "replaced", "narf") and replace(theString, "be", "rafn")


    this "Wont" rafn " replaced, be"

    Can this be done moderately easily?
    I am working on it but haven't gotten far yet...

  2. #2
    Senior Member
    Join Date
    Jul 2013
    Thanked 121 Times in 105 Posts

    Default Re: Replace unless inside quotes?

    Well, easy or hard is relative to your skill. There are many ways how to do this. If you know a lot about regular expressions you could give that a go. You could also try to use the String classes split method to split around quotation marks. Or you might use the charAt method from string to find substring within and outside of quotation marks.

  3. The Following User Says Thank You to Cornix For This Useful Post:

    GregBrannon (August 24th, 2014)

Similar Threads

  1. The case of the disappearing double quotes
    By oldalistair in forum What's Wrong With My Code?
    Replies: 3
    Last Post: May 30th, 2014, 01:36 PM
  2. Looking to replace email msgs with........... something else.
    By paulmac1968 in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: June 4th, 2013, 12:06 PM
  3. Replace bracket
    By marcobelli in forum What's Wrong With My Code?
    Replies: 1
    Last Post: June 4th, 2013, 12:00 PM
  4. [SOLVED] to replace a word in file
    By shenaz in forum What's Wrong With My Code?
    Replies: 20
    Last Post: March 21st, 2013, 01:53 PM
  5. Using the replace method?
    By jean28 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: September 22nd, 2012, 04:17 PM