Pattern matching for a string starting with character and ending with digit

时间:2015-10-30 22:22:21

标签: javascript regex

Here is a valid string that always start with fixed string SOME_START_FORMAT_ then end with one or more digits. So valid strings are

SOME_START_FORMAT_1234
SOME_START_FORMAT_12

Invalid strings are

SOME_INVALID_FORMAT_1234
SOME_START_FORMAT_
SOME_START_FORMAT_1234_
SOME_START_FORMAT_1234_MORE

I am trying with this regex ^SOME_START_FORMAT_\d+$. What I am doing wrong?

Fiddle

2 个答案:

答案 0 :(得分:1)

you need to check for end of string instead of end of line so nothing after the digits will match (\z):

^SOME_START_FORMAT_\d+\z

for multiline this works at regxr.com

/^SOME_START_FORMAT_\d+$/gm

just have to add the multiline flag.

答案 1 :(得分:1)

Your Regex is fine. I think the fiddle is confusing because it treats all of your input as a single String with several new line characters. Your pattern works as expected on individual Strings: var input = [ "SOME_START_FORMAT_1234", "SOME_START_FORMAT_12", "SOME_INVALID_FORMAT_1234", "SOME_START_FORMAT_", "SOME_START_FORMAT_1234_", "SOME_START_FORMAT_1234_MORE" ]; var pattern = /^SOME_START_FORMAT_\d+$/; input.forEach(function(s) { var isMatch = s.match(pattern) !== null; document.write(s + ": " + isMatch + "<br>") })