Matthias Wadlinger
Matthias Wadlinger

Reputation: 21

regex to find strings that start with a backslash

I'm looking for a regular expression that finds Strings that start with a backslash.

"^\", "^\\" and "^\\\" don't work at all and "^\\\\" just finds strings that start with 2 backslashes.

I'm using Java btw.

Upvotes: 0

Views: 2991

Answers (2)

pabaptista
pabaptista

Reputation: 79

Don't forget that \ is a special char in Java. So in order to the regex to detect the \ character you need to escape it on the string. For example "\test" would print as a tab followed by est. "\\test" would be printed correctly.

Regarding the regex itself, it should be "^\\\\" as you need to escape the backslash there as well.

Upvotes: 0

anubhava
anubhava

Reputation: 785246

You don't really need regex here, just use:

boolean b = string.startsWith("\\");

to check if given string starts with a backslash.

Upvotes: 5

Related Questions