Angad
Angad

Reputation: 27

Regex to match [[Wikipedia:Manual of Style#Links|]] # in java

I have been trying to match the following string -

String temp = "[[Wikipedia:Manual of Style#Links|]]" ;

with the regex

boolean a = temp.matches("\\[\\[Wikipedia:[a-zA-Z_0-9]*#[a-zA-Z_0-9]*\\|\\]\\]");

"\\[\\[Wikipedia:(.*?)#(.*?)\\|\\]\\]"

"\\[\\[Wikipedia:(.*)*#(.+)*\\|\\]\\]"

"\\[\\[(.*?)#(.*?)\\|\\]\\]"

But none of them are giving any positive matches.

Upvotes: 0

Views: 107

Answers (3)

Melih Altıntaş
Melih Altıntaş

Reputation: 2535

public static void main(String[] args) {
    String temp = "[[Wikipedia:Manual of Style#Links|]]";
    Pattern pattern = Pattern.compile("\\[\\[Wikipedia:([\\w ]+)#([\\w ]+)\\|\\]\\]");
    Matcher matcher = pattern.matcher(temp);

    if(matcher.find()) {            
        System.out.println("Manual of Style: " + matcher.group(1));
        System.out.println("links : " + matcher.group(2));
    }
}

or

temp.matches("\\[\\[Wikipedia:([\\w ]+)#([\\w ]+)\\|\\]\\]");

Upvotes: 0

Bohemian
Bohemian

Reputation: 425098

Straight away I can see a problem: you are using a character class without a space to match input with spaces.

Try this:

boolean a = temp.matches("\\[\\[Wikipedia:[\\w ]*#[\\w ]+\\|\\]\\]");

Note that [a-zA-Z_0-9] can be replaced by [\w] (but would include letters/numbers from all languages, which should be fine)

Upvotes: 1

Jk1
Jk1

Reputation: 11443

Just add a space to your custom character class:

String temp = "[[Wikipedia:Manual of Style#Links|]]" ;
temp.matches("\\[\\[Wikipedia:[a-zA-Z_0-9 ]*#[a-zA-Z_0-9]*\\|\\]\\]");  //true

Upvotes: 0

Related Questions