I want to know if I would be able to replace different words all in one regex expression. For example if I wanted to replace the name John with Joe and Smith with Doe. Would I be able to do that with one expression?

Here is a code that I have that changes the misspelled name correctly, however I need to replace two more different words with something else:

 Pattern replace = Pattern.compile("nam");
              Matcher match = replace.matcher(words);
            words = match.replaceAll("name");

Recommended Answers

All 8 Replies

I'm not entirely clear on what you are trying to do. can you elaborate a bit on it, please?

I'm no regex expert, but my guess is that you can't, or, if you can, it's ludicrously complex.
The real question is: why? Why not just run two simple replace commands with two simple regexs?

Ok I thought so. So, I would have to do three different pattern complies, correct?

Yes, I think so.

However, I do get extra points if I can do it one line of code. Just to be clear I would have to replace two different words with two different new words that are in one long line of text.

I had a quick Google, and it seems there is a way, but it's far beyond my regex skills to understand it. Just search on "regex multiple replacements" or somesuch.

Could you give an example of what you want to do? Also, are you sure that one line is equal to 1 regex pattern & replace?

From my understanding, you want to replace 2 different words with 2 different values in one regex pattern. If so, I am not so sure you can do that. The reason is that there are 2 parts in this process - match & replace. The matching part is done via regex. Once it found the matched, the replace uses the defined replace value to swap out the matched. I am not so sure that you can have more than 1 set of value used in replacement (you could, however, augment the matched with some other values).

However, if you want to replace 2 different words with the same values, this can be done. What you need may be more complex. The simpliest form (if you match only a letter, is to use []. If you want to match a group of characters, you may use a pair of () to group a pattern you need to match.

However, I do get extra points if I can do it one line of code. Just to be clear I would have to replace two different words with two different new words that are in one long line of text.

Is using regex a requirement here? You can do this simply by chaining replace or replaceAll calls since the return the updated result string. Also, when you say single line, does it mean just one regex (and the supporting helper code) or literally a single line?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.