0

I am finding it a bit difficult to wrap my head around prefix and suffix lookups in regular expressions. I am practicing and want to do the following:

Given a string: "James is good". I want to be able to match the maximal substring in-order, i.e get a match if the text is "James"or "James is" or "James is good". So if I have the following text: "James James is James", I should be able to capture "James is" and not just "James". Simalrly " is James James is Good James" should give me "James is Good" and not "is James" as it is out of order and not maximal

I think i can use suffix is not present(?!), to match, say only "James" if "is good" is not present and so on, but I am not sure if I understand the concept of prefix and suffix matching correctly.

Any clarification or help in this case would be great. I tagged java because I am familiarizing myself with java's regex api.

2 Answers 2

1

I think you mean that you want to capture "James is" and the next word if exists. In this case you should say "(James is(?:\s+\w+)?)". Obviously in java code the back slashes must be duplicated.

I have not run this regex but I believe it can give a good start to debug yours.

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

1 Comment

Thanks for the quick reply! Yes, but I want to capture the next word only if it's "good". Otherwise I want "James is". Same thing with "James" and "is". I want to capture "James" if the next word is not "is". Otherwise I want "James is".
0

I am not sure, but I assume you are talking about look behind and look ahead assertions.

An assertion has zero length and is matching the empty string, so no characters are matched by this construct. You can use them to match a pattern only if it is preceded or followed by a certain other pattern (or not if you use the negative versions)

You can check here for more details on regular-expressions.info

The Perlretut is about Perl, but it works similarly in Java.

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.