Regular expression to match optional numeric string
I'm trying to build a regular expression to match a string somthing like
Sample:
3232asdfADFF/ew323fdffADF 4243dsafAFDF 232 (total 42)
<----p1---->/<---p2-----> <----p3----> P4
I could successfully match till p3
but unab开发者_JS百科le to match last part i.e. p4
The p4
is essentially numeric string, having length 0 to 3 (abscent or max 3).
I'm using:
[0-9A-Za-z]{2,12}/[0-9A-Za-z]{3,12} [0-9A-Za-z]{0,12}\\b \\d{0,3}$
But the problem I'm facing is that it fails if I completely remove p4
from input.
And succeeds with even if on number.
This should work for you, I think:
[0-9A-Za-z]{2,12}/[0-9A-Za-z]{3,12}(?: [0-9A-Za-z]{1,12})?(?: \\d{1,3})?$
Of course it fails if you have no space. You should have something like ( \d{0,3})?$
I think.
As I mentioned in a comment, not sure what may/may not exist in the pattern. But, best guess effort, here's what I've come up with:
\w{3,12}\/\w{3,12} (?:\w{0,12} )?\d{0,3}
That will match everything up until the (total 42)
. If you need to include that as well, you can add:
(?: \(\w+ \d+\))?
To the end of the pattern. Again, best effort based on what I see and what I'm guessing should be the result. If it's not what you're going for, leave me a comment and I can adjust it.
(Also, for the sake of length I replaced the [0-9a-zA-Z]
with \w
. Though it's not a direct one-to-one replacement, it was close. If you need it to be explicitly the previous pattern, replace the \w
back to your original class.)
精彩评论