简体   繁体   中英

Java Regex Prefix Suffix

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, ie 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM