Regexp for specific matching of character string

萝らか妹 提交于 2019-12-25 02:12:54

问题


I need a regex to match something like

"4f0f30500be4443126002034"

and

"4f0f30500be4443126002034>4f0f31310be4443126005578"

but not like

"4f0f30500be4443126002034>4f0f31310be4443126005578>4f0f31310be4443126005579"


回答1:


Try:

^[\da-f]{24}(>[\da-f]{24})?$

[\da-f]{24} is exactly 24 characters consisting only of 0-9, a-f. The whole pattern is one such number optionally followed by a > and a second such number.




回答2:


I think you want something like:

/^[0-9a-f]{24}(>[0-9a-f]{24})?$/

That matches 24 characters in the 0-9a-f range (which matches your first string) followed by zero or one strings starting with a >, followed by 24 characters in the 0-9a-f range (which matches your second string). Here's a RegexPal for this regex.




回答3:


Don't need a regex.

str = "4f0f30500be4443126002034>4f0f31310be4443126005578"

match = str.count('>') < 2

match will be set to true for matches where there are 1 or 0 '>' in the string. Otherwise match is set to false.



来源:https://stackoverflow.com/questions/8854363/regexp-for-specific-matching-of-character-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!