Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

regex - Regular expression matching a sequence of consecutive words with spaces except for the last space

I have a list of words and I want to match any combination of those words. Assume that I have the words apple, orange and mango and I am working with the following string:

This place has the best apple pie. They also have orange, apple and mango-apple smoothie ... 

The regular expression that I have so far is ((apple|orange|mango)[s-(,s)]*)+

It matches the right combination of words but additionally it matches an extra space at the end of the sequence. The matches I get:

"apple "
"orange, apple "
"mango-apple "

I know why it does that. How can I change the regular expression to get rid of that last space at the end?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Adding a at the end seems to have worked for me. Also, the - should be put last when placed in square brackets. So, all you need to do is to change your regex to this: ((apple|orange|mango)[s(,s)-]*)+

EDIT:

As per your comment, I have tried out this: ((apple|orange|mango)([s,-]+(apple|orange|mango))*)+. The problem with your current regex is that you are also throwing in the spaces at the end so that you could match apple mango for instance.

The regex I propose should match the spaces, dashes or commas if and only if they are followed by the words apple, orange or mango.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...