I have been struggling with this and would appreciate any help.
I have a line of code that always looks like this:
Thread.sleep(1000)
Thread.sleep()
is always a fixed sequence of characters, but the integer number inside is variable. How would I write a regular expression to catch this?
You can use the regex, Thread\s*\.\s*sleep\s*\(\s*\d+\s*\)
.
Explanation of the regex:
Thread
: Literal, Thread
\s*\.\s*
: .
preceded by and followed by 0+ whitespace characterssleep\s*
: Literal, sleep
followed by 0+ whitespace characters\(\s*
: The character, (
followed by 0+ whitespace characters\d+\s*
: One or more digits followed by 0+ whitespace characters\)
: The character, )
Demo:
public class Main {
public static void main(String[] args) {
String x = "Some Thread.sleep(1000) text";
x = x.replaceAll("Thread\\s*\\.\\s*sleep\\s*\\(\\s*\\d+\\s*\\)", "");
System.out.println(x);
}
}
Output:
Some text