-1

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?

esqew
  • 42,425
  • 27
  • 92
  • 132
user3325294
  • 89
  • 2
  • 11
  • You want to get the '1000' part from `Thread.sleep(1000)`? The integer number inside is constant not variable. 1000 is not changing. What is your goal anyways? Seems like an XY problem to me. – Yoshikage Kira Jun 17 '21 at 17:18
  • We have many lines of code like Thread.sleep(1000) or Thread.sleep(100) or Thread.sleep(2500). We have written a special function to replace this. I wish to do a RegExp search through the code for these lines and replace them with the new function. – user3325294 Jun 17 '21 at 17:29
  • @user15793316 Even better would be `Thread\.sleep\s*(\d+\)`. Inside a Java string, that would be `"Thread\\.sleep\\s*\\(\\d+\\)"`. Sometimes there can be whitespace before the `()`. – Amal K Jun 17 '21 at 17:36

1 Answers1

4

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 characters
  • sleep\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
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110