Replace all words in java

Java String replaceAll()

The String.replaceAll(regex, replacement) in Java replaces all occurrences of a substring matching the specified regular expression with the replacement string.

A similar method replace(substring, replacement) is used for matching the literal strings, while replaceAll() matches the regex. Note that in regular expressions, literal strings are also patterns, so replaceAll() will work with literal strings as well, in addition to regex patterns.

The syntax of the replaceAll() API is as follows:

String updatedString = thisString.replaceAll(regex, replacement);
  • thisString: the string that should be searched for substring pattern and modified.
  • regex: pattern to be searched.
  • replacement: each occurrence of the matches will be replaced with this substring.
  • updatedString: the result of the API that is the modified string.

2. String.replaceAll() Example

The following Java program demonstrates the usage of replaceAll() API.

2.1. Replace All Occurrences of a Word

The following Java program replaces all occurrences of “java” with “scala“.

String str = "how to do in java !! a java blog !!"; Assertions.assertEquals("how to do in scala !! a scala blog !!", str.replaceAll("java", "scala"));

2.2. Remove All Whitespaces

The following Java program replaces all occurrences of whitespaces in a string with an empty string.

String blog = "how to do in java"; Assertions.assertEquals("howtodoinjava", blog.replaceAll("\\s", ""));

We should know that replaceAll() throws PatternSyntaxException if the regex’s syntax is NOT valid. In the given example, “[” is an invalid regular expression, so we get the exception in runtime.

Assertions.assertThrows(PatternSyntaxException.class, () -> < blog.replaceAll("[", ""); >);

Источник

Replace all words in java

So try Or even better to reduce explicit escaping in replacement part (and also in regex part — forgot to mentioned that earlier) just use instead which adds regex escaping for us Solution 4: This doesn’t say how to «fix» the problem — that’s already been done in other answers; it exists to draw out the details and applicable documentation references. So, Try: output: Solution 2: Use replace() output: Solution 3: Let’s take a tour of String#repalceAll(String regex, String replacement)

Replace all words in java

I’m using the java replaceAll() method for replace matching words in a string. In my case If this word is next to a comma (,) fullstop (.) or anything else like that, this word is not replacing.

body = body.replaceAll("(?i) "+knownWord + " ", replaceWord); 

Can anyone please suggest me an regular expression which is capable of identifying all the words in this string?

Regular expression visualization

It finds (and captures) words as long as they are not next to commas or periods. Just add whatever punctuation marks you like to the character-classes, such as [. (] .

As far as ignoring case, just pass the CASE_INSENSITIVE flag to your Pattern object, such as with

Pattern p = Pattern.compile(theAbovePattern, Pattern.CASE_INSENSITIVE); 

If you want to match specific knownWord do:

 body = body.replaceAll("(?i)\\b"+knownWord + "\\b", replaceWord); 

I think what you were looking for is the \\b (word boundary) it is used to detect where words start/end, so commas or dots should no longer be a problem then.

More detailed example in response to your comment:

 String body = "I'm going to school. "; String knownWord = "school"; String replaceWord = "shop"; System.out.println(body.replaceAll("(?i)\\b"+knownWord + "\\b", replaceWord)); 

The above will print out the following:

Java replace all method appending the replacement string instead, Use data.replaceAll(«\\b[AEIOUaeiou]\\w*»,»XXXXX»); or to only match letters, replace \w

Replace(), replaceAll(), replaceFirst() Methods of String in

Java RegEx to replace a string where the beginning and end part match a specific pattern

Hi I need to write a regular expression in java that will find all instances of :

wsp:rsidP="005816D6" wsp:rsidR="005816D6" wsp:rsidRDefault="005816D6" 

attributes in an XML string and strip them out:

So I need to rip out all attributes that starts with wsp:rsid and ends with a double quote ( » )

xmlstring.replaceAll( "wsp:rsid\\w*?=\".*?\"", "" ); 
public void testReplaceAll() throws Exception < String regex = "wsp:rsid\\w*?=\".*?\""; assertEquals( "", "wsp:rsidP=\"005816D6\"".replaceAll( regex, "" ) ); assertEquals( "", "wsp:rsidR=\"005816D6\"".replaceAll( regex, "" ) ); assertEquals( "", "wsp:rsidRDefault=\"005816D6\"".replaceAll( regex, "" ) ); assertEquals( "a=\"1\" >", "a=\"1\" wsp:rsidP=\"005816D6\">".replaceAll( regex, "" ) ); assertEquals( "bob kuhar", "bob wsp:rsidP=\"005816D6\" wsp:rsidRDefault=\"005816D6\" kuhar".replaceAll( regex, "" ) ); assertEquals( " keepme=\"yes\" ", "wsp:rsidP=\"005816D6\" keepme=\"yes\" wsp:rsidR=\"005816D6\"".replaceAll( regex, "" ) ); assertEquals( "", "".replaceAll( regex, "" ) ); // Sadly doesn't handle the embedded \" case. // assertEquals( "", "wsp:rsidR=\"hello\\\"world\"".replaceAll( regex, "" ) ); > 
xmlstring.replaceAll("\\bwsp:rsid\\w*=\"[^\"]+(\\\\\"[^\"]*)*\"", ""); 

Also, your regexes are wrong. I suggest you go and plough through http://regular-expressions.info 😉

Here are 2 functions. clean will do the replacement, extract will extract the data (if you want it, not sure)

Please excuse the style, I wanted you to be able to cut and paste the functions.

import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Answer < public static HashMapextract(String s) < Pattern pattern = Pattern.compile("wsp:rsid(.+?)=\"(.+?)\""); Matcher matcher = pattern.matcher(s); HashMaphm = new HashMap(); //The first group is the string between the wsp:rsid and the = //The second is the value while (matcher.find()) < hm.put(matcher.group(1), matcher.group(2)); >return hm; > public static String clean(String s) < Pattern pattern = Pattern.compile("wsp:rsid(.+?)=\"(.+?)\""); Matcher matcher = pattern.matcher(s); return matcher.replaceAll(""); >public static void main(String[] args) < System.out.print(clean("sadfasdfchri wsp:rsidP=\"005816D6\" foo=\"bar\" wsp:rsidR=\"005816D6\" wsp:rsidRDefault=\"005816D6\"")); HashMapm = extract("sadfasdfchri wsp:rsidP=\"005816D6\" foo=\"bar\" wsp:rsidR=\"005816D6\" wsp:rsidRDefault=\"005816D6\""); System.out.println(""); //ripped off of http://stackoverflow.com/questions/1066589/java-iterate-through-hashmap for (String key : m.keySet()) < System.out.println("Key: " + key + ", Value: " + m.get(key)); >> > 
sadfasdfchri foo="bar" Key: RDefault, Value: 005816D6 Key: P, Value: 005816D6 Key: R, Value: 005816D6 

Unlike all other answers, this answer actually works!

xmlstring.replaceAll("\\bwsp:rsid\\w*?=\"[^\"]*\"", ""); 

Here’s a test that fails with all other answers:

public static void main(String[] args) < String xmlstring = "hello"; System.out.println(xmlstring); System.out.println(xmlstring.replaceAll("\\bwsp:rsid\\w*?=\"[^\"]*\"", "")); > 

Java regex text replace, You may trim the string from non-word chars on both ends (with .replaceAll(«^\\W+|\\W+$», «») ), and then replace 1 or more non-word

Java: Replace all ‘ in a string with \’

I need to escape all quotes (‘) in a string, so it becomes \’

I’ve tried using ReplaceAll, but it doesn’t do anything. For some reason I can’t get the regex to work.

String s = "You'll be totally awesome, I'm really terrible"; String shouldBecome = "You\'ll be totally awesome, I\'m really terrible"; s = s.replaceAll("'","\\'"); // Doesn't do anything s = s.replaceAll("\'","\\'"); // Doesn't do anything s = s.replaceAll("\\'","\\'"); // Doesn't do anything 

I’m really stuck here, hope somebody can help me here.

You have to first escape the backslash because it’s a literal (yielding \\ ), and then escape it again because of the regular expression (yielding \\\\ ). So, Try:

You\'ll be totally awesome, I\'m really terrible 

You\’ll be totally awesome, I\’m really terrible

Let’s take a tour of String#repalceAll(String regex, String replacement)

An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

Pattern.compile(regex).matcher(str).replaceAll(repl)

So lets take a look at Matcher.html#replaceAll(java.lang.String) documentation

Note that backslashes ( \ ) and Dollar signs ( $ ) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string .

You can see that in replacement we have special character $ which can be used as reference to captured group like

System.out.println("aHellob,aWorldb".replaceAll("a(\\w+?)b", "$1")); // result Hello,World 

But sometimes we don’t want $ to be such special because we want to use it as simple dollar character, so we need a way to escape it.
And here comes \ , because since it is used to escape metacharacters in regex, Strings and probably in other places it is good convention to use it here to escape $ .

So now \ is also metacharacter in replacing part, so if you want to make it simple \ literal in replacement you need to escape it somehow. And guess what? You escape it the same way as you escape it in regex or String. You just need to place another \ before one you escaping.

So if you want to create \ in replacement part you need to add another \ before it. But remember that to write \ literal in String you need to write it as «\\» so to create two \\ in replacement you need to write it as «\\\\» .

Or even better

to reduce explicit escaping in replacement part (and also in regex part — forgot to mentioned that earlier) just use replace instead replaceAll which adds regex escaping for us

This doesn’t say how to «fix» the problem — that’s already been done in other answers; it exists to draw out the details and applicable documentation references.

When using String.replaceAll or any of the applicable Matcher replacers, pay attention to the replacement string and how it is handled:

Note that backslashes ( \ ) and dollar signs ( $ ) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

As pointed out by isnot2bad in a comment, Matcher.quoteReplacement may be useful here:

Returns a literal replacement String for the specified String. .. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes ( \ ) and dollar signs ( $ ) will be given no special meaning.

Java replace all String add quotations around all words but ignore, String data = «JavaScript, Spring 4.0» String result = data.replaceAll(«(\\w+)», «\»$1\»»); result = «[» +

Источник

How to replace all occurrences of a word in a string with another word in java?

The replaceAll() method of the String class accepts two strings, One representing a regular expression to find a string and the other representing a replacement string.

And, replaces all the matched sequences with the given String. Therefore, to replace a particular word with another in a String −

  • Get the required String.
  • Invoke the replace all method on the obtained string by passing, a regular expression representing the word to be replaced (within word boundaries “\b”) and a replacement string as parameters.
  • Retrieve the result and print it.

Example

import java.io.File; import java.io.IOException; import java.util.Scanner; public class ReplacingWords < public static void main(String[] args) throws IOException < Scanner sc = new Scanner(new File("D://sample.txt")); String input; StringBuffer sb = new StringBuffer(); while (sc.hasNextLine()) < input = sc.nextLine(); sb.append("
"+input); > String contents = sb.toString(); System.out.println("Contents of the string: "+contents); contents = contents.replaceAll("\bTutorials point\b", "TP"); System.out.println("Contents of the string after replacement: "); System.out.println(contents); > >

Output

Contents of the string: Tutorials point originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. At Tutorials point we provide high quality learning-aids for free of cost. Tutorials point recently developed an app to help students from 6th to 12th. Contents of the string after replacement: TP originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. At TP we provide high quality learning-aids for free of cost. TP recently developed an app to help students from 6th to 12th.

Источник

Читайте также:  Java string double to integer
Оцените статью