在字符类中使用$锚不起作用 [英] Using $ anchor inside a character class does not work

查看:48
本文介绍了在字符类中使用$锚不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个正则表达式以匹配具有第一个10个字母大写字母数字的字符串,然后匹配一个空格和一些其他文本或具有第1个10个字母数字字符的字符串, $ 可以似乎没有用.

我写了这个 [A-Z0-9] {10} [\ s $].* ,对于具有10个字符,一个空格和一些东西但不起作用的字符串来说,它似乎可以正常工作仅在字母数字后结束的字符串.

例如

 "MNA345QWRE ABC"被匹配"MNA345QWRE"不匹配 

解决方案

[...] 中的 $ 符号按字面意义处理.使用交替要求后跟空格"或行尾":

  [A-Z0-9] {10}(?:\ s.* | $) 

演示: https://regex101.com/r/f4ufzx/1

I am trying to write a Regex to match a String having 1st 10 characters capital-alpha numeric and then a space and some other text or a String having 1st 10 alpha numeric characters, the $ does'nt seem to work.

I wrote this [A-Z0-9]{10}[\s$].* which seems to work fine for strings having 10 charater then a space and some stuff but not working for string that end just after alpha numeric.

E.g.

"MNA345QWRE ABC" gets matched 
"MNA345QWRE" not matched

解决方案

The $ symbol in [...] is treated literally. Use alternation to require either "space followed by something" or "end of line":

[A-Z0-9]{10}(?:\s.*|$)

Demo: https://regex101.com/r/f4ufzx/1

这篇关于在字符类中使用$锚不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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