dqc2017 2013-01-09 20:12
浏览 95

正则表达式查找除x,a,n, - 之外的所有字符

This is my first post here. I've started writing a few and always managed to figure it out on my own. Alas, regular expressions make me want to beat my face on the street and I'm stuck.

I'm trying to write a regular expression that will check a string for any character that isn't an x, a, n, or -. Here's what I have:

    preg_replace( '/^[^xan\-]+$/' , 'x' , $this->str_key_mask )

I'm sure it's something simple, but I've tried adding, changing, and removing metacharacters and can't get the result I want.

For instance, if I pass in xan-nax-jxy, I want to get back xan-nax-xxx due replacing the j and y with x. If I pass in xxx-aaa-nnn, it should return xxx-aaa-nnn since nothing needs replacing.

  • 写回答

3条回答 默认 最新

  • doujuanju3076 2013-01-09 20:15
    关注

    With the ^ and $ anchors, you will only match strings that are composed of entirely characters that are not x, a, n, or -. Since you want to match each of those characters separately and replace each one with 'x', just remove the anchors and the repetition:

    preg_replace( '/[^xan\-]/' , 'x' , $this->str_key_mask )
    

    Removing the repetition is necessary if you want a string like 'jy' to become 'xx'. If instead you want 'jy' to become 'x', keep the + after your character class so that consecutive characters are replaced together.

    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)