0

I am out of luck getting a regex build together which machtes everything but a specific character not preceded by a specific string.

For example this String:

Mr. Jones likes fish.

Should match like this:

Mr. Jones likes fish

And not for example:

Mr

I think this should be really easy but it just won't work. I already have it working for getting a correct match on the dot:

(?<!Mr)\.

The complementary match won't work though. I tried this:

(?<!Mr)[^.]*

Because i thought the cursor would be on the dot at that point and see that it was proceded by the "Mr" and it won't match. But it does.

And something like this:

(^((?<!Mr).))*

But the lookbehind in that regex is not recognized as one anymore and it just tries to match each character.

I already saw this answer but i couldn't find anythin helping me there.

8
  • 1
    Your question is good apart from the last paragraph (im struggling, help me fast etc). Commented Jun 10, 2018 at 18:13
  • Is the specific string "Mr"? Commented Jun 10, 2018 at 18:14
  • So you want a regexp to match anything except strings that has a \. after Mr somewhere? IsMr always in the string only once? Commented Jun 10, 2018 at 18:16
  • 1
    Sounds to me like you want to match any character besides the period with the exception it is preceded by Mr so the regex could be "(?:[^.]+|(?<=Mr)\\.)+" Commented Jun 10, 2018 at 18:22
  • 1
    @bobblebubble If you post you comment as an answer, I can accept it. Commented Jun 10, 2018 at 18:37

1 Answer 1

2

As it looked to me, you want to match any character besides . with the exception that the period is preceded by Mr so you could use an alternation (or an optional group) and a lookbehind.

(?:[^.]+|(?<=Mr)\.)+

As a Java String: "(?:[^.]+|(?<=Mr)\\.)+"

Here is a demo at regex101 (non Java)

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

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.