开发者

regular expression to match one or more of char a or just one of char b

I am taking user input through UI, and I have to validate it. Input text should obey the following ondition

It should either end with one or more white space characters OR with j开发者_如何转开发ust single '='

I can use

".*[\s=]+"

but it matches multiple '=' also which I don't want to. Please help.


You can use alternation:

(\s+|=)$

This expression means match one or more whitespace character or one equals, at the end of the string. The $ is an anchor which matches the end of the string (as you mentioned you're looking for characters at the end of the string).

(As tchrist correctly pointed out in the comments, $ matches the end of line instead of end of string when in multiline mode. If this is true in your case, and you are indeed looking for the end of the string instead of the end of the line, you can use \Z instead, which matches the end of the string regardless of multiline mode.)


If you want to ensure that there is only one = at the end, you can use a lookaround (in this case, a negative lookbehind, specifically). A lookaround is a zero-width assertion which tells the regex engine that the assertion must pass for the pattern to match, but it does not consume any characters.

(\s+|(?<!=)=)$

In this case, (?<!=) tells the regex engine, the character before the current position cannot be an =. When put into the expression, (?<!=)= means that the = will only match if the previous character is not also a =.


Begin string

Anything not "=" ( to avoid the double "==")

One or more blank spaces OR one "="

End of string

^([^=]*[\s+|=])$

Should work :-)


Try this expression:

".*(\\s+|=)" 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜