问题
I am trying to match a string which is not start and and with (.)dot and allow some special char like underscore(_) in string i found dot match regex but not able to match special character what i have done
preg_match('/^(?![.])(?!.*[.]$).*$/', $str)
Not allowed
.example
example.
example?ghh. (or some more special char not allowed in string)
allowed
exam.pl56e
exmple_
_example_
exam_ple
So string will be
1. Not start with dot but in the middle can be a dot(.)
2. String Not allow special char (&%$#@) etc. But allow alpha numeric, underscore
3. Not end with dot(.)
It's matching start and end dot correctly but i need to improve it to not allow all special character like (!&%)
etc. Just allow given special character.
Thanks
回答1:
You may use
'~^(?!\.)[\w.]*$(?<!\.)~'
See the regex demo
Details:
^
- start of string(?!\.)
- a.
cannot be the first char[\w.]*
- 0 or more letters, digits,_
or.
chars (replace*
with+
to match at least 1 char in the string to disallow an empty string match)$
- end of string(?<!\.)
- last char cannot be.
回答2:
How about:
^\w[\w.]*\w$
This is matching alphanum or underscore, optional dot in the midle then alphanumeric or underscore.
NB: It matches strings greater or equal to 2 characters.
This one matches strings with at least one character long.
^(?!\.)[\w.]+$(?<!\.)
回答3:
preg_match('/^[^.].*[^.]$/', $str)
if you need to avoid dot from a beginning and end of the string you want use the class [^.]
The .* tels you that you allow all chars in a string. If your goal is to restrict some chars inside a string you can use [^......] before dot.
preg_match('/^[^.][^?*].*[^.]$/', $str)
来源:https://stackoverflow.com/questions/45058309/regex-to-find-not-start-and-end-with-dot-and-allow-some-special-character-only-n