开发者

What regular expression finds four digits before and after an "x"?

What would be a regular expression to find the four digits in front of and after the "x" in the following strings:

234a2343x2834o234 --> 2343, 2834
iur3333x4开发者_JAVA技巧4445555 --> 3333, 4444
owier3423x23sd --> 3423, no match


Using Perl regex:

/(\d{4})?x(\d{4})?/

Note the capture groups and ? for each 4-digit number. You didn't specify, but if the number at the left side is mandatory, drop the first ?.


(\d{4})x(\d{4})? would work for Perl compatible regular expressions.


([0-9]{4})?x([0-9]{4})?

See on rubular: http://www.rubular.com/r/PhsyDdc1ad

This will return the four digits before and after the first x. If there are fewer than 4 digits, as in your third example, there will be an empty group but the regex will still match to potentially return the digits on the other side of x.

Note that some regular expression engines define the character group \d to contain the digits 0, 1, ..., 9. If you're using one of them you can condense the expression to:

(\d{4})?x(\d{4})?
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜