正则表达式查找不以点开头和结尾,只允许一些特殊字符而不是全部 [英] Regex to find not start and end with dot and allow some special character only not all

查看:29
本文介绍了正则表达式查找不以点开头和结尾,只允许一些特殊字符而不是全部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试匹配一个不是以 (.)dot 开头的字符串,并允许在字符串中使用一些特殊字符,例如下划线 (_)我发现点匹配正则表达式但无法匹配我所做的特殊字符

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)

不允许

.example
example.
example?ghh. (or some more special char not allowed in string)

允许

 exam.pl56e
    exmple_
    _example_
    exam_ple

所以字符串将是

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

推荐答案

您可以使用

'~^(?!\.)[\w.]*$(?<!\.)~'

查看正则表达式演示

详情:

  • ^ - 字符串的开始
  • (?!\.) - . 不能是第一个字符
  • [\w.]* - 0 个或多个字母、数字、_. 字符(替换 *code> 与 + 匹配字符串中至少 1 个字符以禁止空字符串匹配)
  • $ - 字符串结束
  • (?<!\.) - 最后一个字符不能是 .
  • ^ - 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 .

这篇关于正则表达式查找不以点开头和结尾,只允许一些特殊字符而不是全部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆