Mohammad Fajar
Mohammad Fajar

Reputation: 1007

Java regular expression: Matches back slash character

How to macth a backslah (\) in java regular expression? I hava some sript to matching all latex tag In some file but it didnt work.

public class TestMatchTag {

    public static void main(String[] args) {

        String tag = "\begin";

        if (Pattern.matches("\\\\[a-z]+", tag)) {
            System.out.println("MATCH");
        }
    }

}

Upvotes: 2

Views: 3549

Answers (4)

Murthy
Murthy

Reputation: 387

This should work...

Pattern.matches("\\[a-z]+", tag);

[a-z] allows any character between a-z more than once and \\ allows "\" once.

you can validate your expression online here

Upvotes: -1

user2018791
user2018791

Reputation: 1153

You need another backslash to escape the "\" in "\begin", change it to "\begin", otherwise the "\b" in your "\begin" will be considered as one character.

Upvotes: 0

newuser
newuser

Reputation: 8466

Try this,

Pattern.matches("[\\a-z]+", tag)

Upvotes: 2

Oleg Estekhin
Oleg Estekhin

Reputation: 8395

Replace String tag = "\begin"; with String tag = "\\begin";. The regex is valid, but your input string needs to escape \ character.

Upvotes: 2

Related Questions