问题
quick question -
How do you create a language of strings out of say {x,y}, but negating all strings with (xy)?
My attempt's so far:
\bx*[^(xy)]*y\b
OR \by*[^(xy)]*x\b
OR \b[^(xy)][xy]*[^(xy)]*\b
The last of which is the least restricted, but seems clumsy with the multiple usage of [^(xy)].
What is the laziest most convenient method for completely negating a string which contains (xy), but allows all other combinations?
Thanks
Editted: Example strings that are allowed: xxxxxxx yyyyyyyyy yxxxx yyyyyyxx
Example strings that are not allowed: xxxxyxxx xyxxxx yyyyxyyy yyyxyxy etc
回答1:
If I understand the challenge correctly, you're describing a language of strings that can start with any number of y's, followed by any number of x's, as those are the only two characters allowed, and you can't place a y once an x has appeared because that would cause the string "xy" to appear.
\by*x*\b
Of course, I assume that you're actually looking for a more general solution for cases that aren't as simple as the one you give. In that case, a negative lookahead assertion is the easiest solution.
回答2:
Use a negative lookahead
\b((?!xy)[xy])+\b
回答3:
Try:
\bx[^xy\s]*y\b
Explanation:
<!--
\bx[^xy\s]*y\b
Options: ^ and $ match at line breaks
Assert position at a word boundary «\b»
Match the character “x” literally «x»
Match a single character NOT present in the list below «[^xy\s]*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
One of the characters “xy” «xy»
A whitespace character (spaces, tabs, and line breaks) «\s»
Match the character “y” literally «y»
Assert position at a word boundary «\b»
-->
来源:https://stackoverflow.com/questions/10294509/regex-negating-characters