0

I'm trying to match a hyphen in all situations except when it is preceded by whitespace and proceeded by non-whitespace.

x-y   //match
x - y //match
x- y  //match
x -y  //not match

I want the regex to determine a match based on the above requirements but only capture the negative sign. Is this possible?

Thanks!

Edited for accuracy.

2
  • 2
    It seems you're example and requirement don't match. Could you be more accurate? Commented Mar 20, 2011 at 3:20
  • You're right Steinar. I fixed up the question. Commented Mar 20, 2011 at 3:30

2 Answers 2

4

It's possible using a negative lookbehind and a positive lookahead assertion (docs):

(?<!\s)-|-(?=\s)

Which says: Match any hyphen either (not preceded by whitespace) or (proceeded by whitespace). This is the same as saying "not (preceded by whitespace) and (proceeded by non-whitespace)", according to De Morgan's laws.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Cameron. Sorry for the ambiguity in the question too; I changed it so my description matches my examples now.
0

You could employ multiple alternatives, one for each case:

Pattern regex = Pattern.compile(
    "  (?<=\\S)-(?=\\S)  # x-y   //match\n" +
    "| (?<=\\s)-(?=\\s)  # x - y //match\n" +
    "| (?<=\\S)-(?=\\s)  # x- y  //match", 
    Pattern.COMMENTS);

This logic could probably be shortened (at the expense of some readability).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.