-3

I am new to regex. I need a regex for JavaScript code that allows special character * in the beginning of text input, but not anywhere else in the text.

example : it should allow *text, it should not allow *text*abcd

I would need a similar regex for PHP as well.

I have tried using "/^\s*/", but this doesn't work. Anyways I dont have anyidea of regex. I have started learning it.

Thanks Dora

4

7 回答 7

5

学习如何使用正则表达式的一部分是知道什么时候不需要它。在这种情况下,对于 PHP,没有正则表达式的解决方案就足够了:

if (strrpos($str, '*') > 0) {
  // invalid position of *
}

对于 JavaScript:

if (str.lastIndexOf('*') > 0) {
    // invalid position for *
}

它基本上找到了特殊字符的最后一个位置;如果它出现在字符串中并且不是第一个字符,则条件内的代码将被执行。

于 2012-06-05T13:00:37.190 回答
3
^\*?[^*]+$
  • 均值从字符串的^开头匹配
  • \*?可选匹配 a (*表示?零或一匹配)
  • 匹配一个[^*]+或多个不是*
  • $意味着匹配必须在字符串的最后结束,以确保没有任何额外*的 s

这可以在PHPJavascript中使用。

于 2012-06-05T13:02:30.600 回答
2

应该送你到那里。

^\*[^\*]+$    // forces the first asterisk

^\*?[^\*]+$   // allows the first asterisk
于 2012-06-05T13:00:30.497 回答
1

如果我理解得很好,我认为你应该像这样 \* 那样转义 *,还记得写这个 \\* 以防你在字符串中写正则表达式

于 2012-06-05T13:20:34.260 回答
0

试试这个代码:

/^(\*)?[^*]+/

^符号的意思in the beginning

于 2012-06-05T12:59:00.700 回答
0

试一试这个表达式:

^.?[^*]+$
于 2012-06-05T13:00:21.980 回答
0

试试这个正则表达式:

/^\*[^\*]+$/g

这是jsFiddle中的一个示例。

于 2012-06-05T13:03:17.450 回答