Search code examples
javapattern-matchingmetacharacters

I'm trying to learn about Regular Expressions


1.Based on this code https://docs.oracle.com/javase/tutorial/essential/regex/test_harness.html

Can anyone please explain what is this \"%s\" in

while (matcher.find()) {
        console.format("I found the text" + " \"%s\" starting at " +
        "index %d and ending at index %d.%n",
        matcher.group(),
        matcher.start(),
        matcher.end());
        found = true;
}

I just know that %s is for string.

2.Refering the meta-characters https://docs.oracle.com/javase/tutorial/essential/regex/literals.html is there any explanation for this outputs?

enter image description here


Solution

  • \"%s\" mean you want to put a String between two quotes for example the result can be :

    I found the text "some string"
    //""-------------^           ^
    // %s             ^_________^
    

    %s use for Strings, if you want to use digit you can use %d and so on

    In Java quote should be escaped how? you can use backslash \" so consider I have a String which contain quotes like this Hello "World" how to use this as a String in Java :

    String string = "Hello "World"";  //<<------- this is an error syntax
    

    To solve it, you have to escape the quotes :

    String string = "Hello \"World\"";
                           ^      ^
    

    take a look at https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html