其他教程

其他教程

Products

当前位置:首页 > 其他教程 >

正则表达式

GG网络技术分享 2025-03-18 16:15 1


问题描述:

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.

图片转代码服务由CSDN问答提供

感谢您的意见,我们尽快改进~

功能建议

我有一个正则表达式如下。</ p>

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

</ code> </ pre>

这很好,如果字符串以VK开头,则返回true [ 1-8] [0-9A-Z],例如VK2TEST。 但是,如果在[0-9A-Z]之后,有一个/更多字符的可能性</ strong>,其中一些我需要返回true,其中一些我需要返回false? 例如VK2TEST / P. </ p>

如果我需要返回,让我们说,VK2TEST / P和VK2TEST / M为真,但其他字母数字字符继续/为假,我该如何处理? 这甚至可能吗? 例如...... </ p>

  VK2TEST = true 

VK2TEST / P = true

VK2TEST / P1 = false

VK2TEST / M = true

VK2TEST / MM = false

VK2TEST / QRP = true

</ code> </ pre>

我的研究指向条件子模式,但我真的不知道我是否正朝着正确的方向前进。</ p>

</ div>

网友观点:

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.

超简单正则表达式入门教程

学习正则表达式的唯一方法就是 Learning by doing。

正则表达式是在程序或命令行中查找和替换文本的强大工具。熟悉最常见的正则表达式符号,以及如何使用它们,对于程序员来说是必不可少的技能。

正则表达式是在搜索中需要匹配的特殊字符串,使用范围很广,比如Java、Python等编程语言,grep、sed等命令行,还有vscode、vim等编辑器。

正则表达式的规则太多了,学会后不怎么用就又忘了,介绍各种规则前先分享给你一张图,

强烈建议你点赞收藏,然后每天看一眼,肯定记得比谁都牢。


码字不易,要是觉得这个回答对你很有帮助,给我 @程序员阿德 点赞关注支持一下。

标签:

提交需求或反馈

Demand feedback