changed
changed

Reputation: 2143

Java regular expression: how to include '-'

I am using this pattern and matching a string.

String s = "//name:value /name:value";
if (s.matches("(//?\\s*\\w+:\\w+\\s*)+")) {
  // it fits
}

This works properly.
But if I want to have a string like "/name-or-address:value/name-or-address:value" which has this '-' in second part, it doesn't work.
I am using \w to match A-Za-z_, but how can I include - in that?

Upvotes: 2

Views: 357

Answers (4)

ring bearer
ring bearer

Reputation: 20803

How about

 if (s.matches("/(/|\\w|-|:\\w)+")) {

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799420

[-\w] (Or in a string, [-\\w].)

Upvotes: 0

pierroz
pierroz

Reputation: 7880

I don't know if it answers your question but why not replacing \w+ with (\w|-)+ or [\w-]+ ?

Upvotes: 0

Amber
Amber

Reputation: 527378

Use [\w-] to combine both \w and -.

Note that - should always be at the beginning or end of a character class, otherwise it will be interpreted as defining a range of characters (for instance, [a-z] is the range of characters from a to z, whereas [az-] is the three characters a,z,and-).

Upvotes: 5

Related Questions