EsotericRider
EsotericRider

Reputation: 127

Java regex using Pattern and Matcher

I am trying to use matcher as an expression to find time stamps in my list of strings. Ex (" [00:00:00.000] ") There are white spaces before and after the time stamp

I checked my regex online and it say it is correct but will not work with my java. It just returns false.

String word = " [00:00:00.000] ";
Pattern pattern = Pattern.compile("^\\s[[0-9:.]*]\\s");
Matcher matcher = pattern.matcher(word);
    if(matcher.matches()){
        //Do Stuff
    else
        //Do other Stuff

Upvotes: 1

Views: 367

Answers (3)

m.cekiera
m.cekiera

Reputation: 5395

Try with:

^\\s\\[[0-9:.]*]\\s

You regex doesn't work because you did't escape first [ character, so it is treated as another character class. You can get timestamp by closing it into group: ([0-9:.]*), but also, if your timestamp always look like this, you can get separate time values with:

^\\s\\[(\\d+):(\\d+):(\\d+)\\.(\\d+)*]\\s

it will give you:

  • hrs - group(1),
  • min - group(2),
  • sec - group(3),
  • msec - group(4),

test it in Java:

public static void main(String args[]){
    String word = " [00:00:00.000] ";
    Pattern pattern = Pattern.compile("^\\s\\[(\\d+):(\\d+):(\\d+)\\.(\\d+)*]\\s");
    Matcher matcher = pattern.matcher(word);
    matcher.find();
    System.out.println(matcher.group(1) + ":" + matcher.group(2) + ":"  + matcher.group(3) + "." + matcher.group(4));
}

Upvotes: 1

StefanHeimberg
StefanHeimberg

Reputation: 1465

package test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.assertTrue;
import org.junit.Test;

public class RegexTest {

    @Test
    public void assert_pattern_found() {
        final String word = " [00:00:00.000] ";
        final Pattern pattern = Pattern.compile("^\\s\\[[0-9:.]*\\]\\s");
        final Matcher matcher = pattern.matcher(word);

        assertTrue(matcher.matches());
    }

}

Upvotes: 0

vks
vks

Reputation: 67968

\\s*\\[[0-9:.]*\\]\\s*

Use this.You dont need ^.escape [].See demo.

https://regex101.com/r/eX9gK2/11

If you want timestamps use

\\s*\\[([0-9:.]*)\\]\\s*

and capture the group 1

Upvotes: 2

Related Questions