Java; String Replace (Using Regular Expressions)

Java string replaceAll regex

Try this:

String input = "Hello cat Cats cats Dog dogs dog fox foxs Foxs";
input = input.replaceAll("(?i)\\s*(?:fox|dog|cat)s?", "");

Demo

Java Regex to replace a pattern in a certain string

You can use regex. Lets start with

yourText = yourText.replaceAll("#(\\S+)", "$1");

in regex:

  • \S represents any non-whitespace characters
  • + represents one or more
  • \S+ represents one or more non-whitespace characters
  • (\S+) -parenthesis create group containing one or more non-whitespace characters, this group will be indexed as 1

in replacement

  • $1 in replacement allows us to use content of group 1.

In other words it will try to find #non-whitespaces (which and replace it with non-whitespaces part.

But this solution doesn't require # to be start of word. To do this we could check if before # there is

  • whitespace space \s,
  • or start of the string ^.

To test if something is before our element without actually including it in our match we can use look-behind (?<=...).

So our final solution can look like

yourText = yourText.replaceAll("(?<=^|\\s)#(\\S+)", "$1");

Replace All string with Regex in the replacement string?

Another alternative you can try is to use regex look around.

str = str.replaceAll("[a-zA-Z](?=\\d)", "L");

RegEx explanation:

[a-zA-Z](?=\\d)    finds the letter within (a-zA-Z) which has a number after it

Output:

<WLWLWL><L1><FS>123<L2><FS>345<E>

Source: Regex lookahead, lookbehind and atomic groups

More on RegEx Pattern: Class Pattern

replaceAll():

Also replaceAll() does modify the String you pass as parameter but instead the function return a new one since Strings are immutable. From String Java:

public String replaceAll(String regex, String replacement)
Returns:
The resulting String

Replace a string using a regular expression

This is definitively not the best code ever, but you could do something like this:

String globalID = "60DC6285-1E71-4C30-AE36-043B3F7A4CA6";
String regExpr = "^([A-Z0-9]{3})[A-Z0-9]*|-([A-Z0-9]{3})[A-Z0-9]*$|-([A-Z0-9]{2})[A-Z0-9]*";

Pattern pattern = Pattern.compile(regExpr);
Matcher matcher = pattern.matcher(globalID);
String newGlobalID = "";
while (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
newGlobalID += matcher.group(i) != null ? matcher.group(i) : "";
}
}
System.out.println(newGlobalID);

You will need to use a Matcher to iterate over all matches in your input as your regular expression matches subsequences of the input string only. Depending on which substring is matched a different capturing group will be non-null, you could also use named capturing groups or remember where in the input you currently are, but the above code should work as example.

Replacing element inside a Collection by using regular expressions

Your code is resigning the variable item, it will not affect the list contents.

To be able to do that, you might change the type of variable arr to List. With that, you can iterate over it by using the traditional (index based) for loop.

List<String> arr = // initializing the list

for (int i = 0; i < arr.size(); i++) {
String item = replace(arr.get(i)); // method replace provided below
arr.set(i, item);
}

Another option is to use Java 8 replaceAll() method, which expects a function that will be applied to every element in the collection.

arr.replaceAll(str -> replace(str));
public static String replace(String source) {
return source.toUpperCase()
.replaceAll("[LI|]", "1")
.replaceAll("[GB]", "6")
.replace("O", "0");
}

Note that method replaceAll() that expect a regular expression is more expensive than replace(). Hence, when you don't need a regex, its better to use any flavor of replace() (with either char or String arguments).

Here you can benefit from replaceAll() by processing characters L, L and | in one go with a regular expression "[LI|]".

For more information on regular expressions take a look at this tutorial

There's also a minor issue in your code:

  • After toUpperCase() has been applied, it doesn't make sense to try to replace lowercase letters like 'l' or 'i'.
  • There's a clash "b", "6" and "B", "8".

I hope with all these hints you'll be able to manage to get it working.

Java: String.replaceAll(regex, replacement);

You can use the Stream API in Java 8:

int elimiateUserId = 11;
String css1 = "11,22,33,44,55";

String css1Result = Stream.of(css1.split(","))
.filter(value -> !String.valueOf(elimiateUserId).equals(value))
.collect(Collectors.joining(","));

// css1Result = 22,33,44,55

regex to replace string is not working correctly

Try the following statement:

String strMod = str.replaceAll("\\s\\|\\| '-' \\|\\| ", ",");

The strMod variable will contain the modified value.

The key points are:

  • use escape char in the regular expression because the pipe character has a special meaning in the regexp
  • use the result value of the replaceAll method

Replace each char after specific word with * using regex JAVA

You may use

s = s.replaceAll("(?<=\\G(?!^)|to).", "*");

See the regex demo.

Details

  • (?<=\G(?!^)|to) - either the end of the previous successful match or to
  • . - any char but a line break char.


Related Topics



Leave a reply



Submit