Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...