duandu2159 2015-06-12 16:09
浏览 14
已采纳

正则表达式

I have a regex as follows.

'#^(VK[1-8][0-9A-Z]+)#i'

This is fine and will return true if the string begins with VK[1-8][0-9A-Z], for example VK2TEST. But what if, following [0-9A-Z], there is the possibility of a / and more characters, some of which I need to return true and some of which I need to return false? For example VK2TEST/P.

If I need to return, let's say, VK2TEST/P and VK2TEST/M as true, but other alphanumeric characters proceeding the / as false, how do I go about this? Is this even possible? For example...

VK2TEST = true
VK2TEST/P = true
VK2TEST/P1 = false
VK2TEST/M = true
VK2TEST/MM = false
VK2TEST/QRP = true

My research points me to conditional subpatterns, but I don't really know if I'm heading in the right direction with this.

  • 写回答

1条回答 默认 最新

  • donglin9068 2015-06-12 16:20
    关注

    For the following results:

    VK2TEST = true
    VK2TEST/P = true
    VK2TEST/P1 = false
    VK2TEST/M = true
    VK2TEST/MM = false
    VK2TEST/QRP = true
    

    You can use a regexp like the following:

    '#^(VK[1-8][0-9A-Z]+(\/(M|P|QRP))?)$#i'
    

    This syntax is covered in the PHP PCRE Meta-Character Syntax page.

    Here are some tips:

    • \: escape character
    • []: class definition
    • +: one or more quantifier
    • ?: zero or one quantifier
    • (): sub-pattern
    • |: start of alternative branch
    • $: end of subject

    Some notes:

    • If you want one or more of a class, the + should be outside the class, e.g. [1-8]+ to include 11. If you want [1-8] or a +, use [1-8+]. Also, in your example [A-Z+] will match T not the extra EST characters. To match the word TEST, you can us [A-Z]+ with the + outside of the class definition.
    • Slashes, /, need to be escaped, hence \/.
    • If you want to match different substrings you should use a sub-pattern enclosed in () while using the | branch pipe to separate patterns.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端