字符串可以包含任何内容,但必须在整个字符串中有一个星号 (*
),而且星号可以出现在字符串的任何位置。
此外,字符串不应包含任何空格。
以下是有效的字符串:
test*
*_test
test*something
以下是无效字符串:
test_**
**_test
test*something*
test *something
test *
testsomething
*
请有人帮我编写适用于上述情况的正则表达式。
字符串可以包含任何内容,但必须在整个字符串中有一个星号 (*
),而且星号可以出现在字符串的任何位置。
此外,字符串不应包含任何空格。
以下是有效的字符串:
test*
*_test
test*something
以下是无效字符串:
test_**
**_test
test*something*
test *something
test *
testsomething
*
请有人帮我编写适用于上述情况的正则表达式。
^(?!(.*?\*){2,}|.*? |\*$).*?\*.*$
如果要允许制表符(其他所有空白字符),请使用\s
,而不是字面上的Space():
^(?!(.*?\*){2,}|.*?\s|\*$).*?\*.*$
它的工作原理:
^ # String starts with ...
(?! # DO NOT match if ...
(.*?\*) # Optional Data followed by a *
{2,} # Multiple times (multiple *s)
| # OR
.*?\s # Optional Data followed by whitespace
| # OR
\*$ # * then the end of the string (i.e. whole string is just a *)
)
.*? # Optional Data before *
\* # *
.* # Optional Data after *
$ # ... String ends with
演示:
strings = [
'test*',
'*_test',
'test*something',
'test',
'*',
'test_**',
'**_test',
'test*something*',
'test *something',
'test *'
]
for (var i = 0; i < strings.length; i++) {
if (strings[i].match(/^(?!(.*?\*){2,}|.*?\s|\*$).*?\*.*$/)) {
document.write(strings[i] + '<br>')
}
}
/^[^*\s]*\*[^*\s]*$/
进行字符串检查,它包含一个星号并且没有空格。如果仅一个星号是无效的,则应添加前瞻以检查至少两个字符的存在,如 /^(?=.{2})[^*\s]*\*[^*\s]*$/
请参见 https://regex101.com/r/yE5zV2/1 的一些示例(转到单元测试)这些条件几乎不需要正则表达式(但在检查空格时使用很好)。
// This is the checking function
function checkStr(x) {
return (x.indexOf("*", x.indexOf("*")+1) === -1 && x.indexOf("*") > -1 && !/\s/.test(x));
}
// And this is the demo code
var valid = ["123*567", "*hereandthere", "noidea*"];
var invalid = ["123*567*", "*here and there", "noidea**", "kkkk"];
valid.map(x => document.body.innerHTML += "<b>" + x + "</b>: " + checkStr(x) + "<br/><b>");
invalid.map(x => document.body.innerHTML += "<b>" + x + "</b>: " + checkStr(x) + "<br/><b>");
POI 是 return (x.indexOf("*", x.indexOf("*")+1) === -1 && x.indexOf("*") > -1 && !/\s/.test(x));
:
x.indexOf("*", x.indexOf("*")+1) === -1
- 确保没有两个星号x.indexOf("*") > -1
- 确保至少有一个 *
!/\s/.test(x)
- 确保字符串中没有空格。var regex = /^([^ \*]|\s)*\*{1}([^ \*]|\s)*$/
var str1 = '*abcfkdsjfksdjf';
var str2 = 'abcfkds*jfksdjf';
var str3 = 'abcfkdsjfksdjf*';
var str4 = 'abcfkdsjfksdjf';
var str5 = 'abcf*kdsjfk*sdjf';
console.log(regex.test(str1)); // returns true;
console.log(regex.test(str2)); // returns true;
console.log(regex.test(str3)); // returns true;
console.log(regex.test(str4)); // returns false;
console.log(regex.test(str5)); // returns false;
^(?:(?!\*)\S)*\*(?:(?!\*)\S)*$
- Avinash Raj