使用带有正斜杠的正则表达式查找字符串 [英] Find a string using regex with forward slashes in it

查看:679
本文介绍了使用带有正斜杠的正则表达式查找字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在下面的示例中找到带有正则表达式的字符串,以dd300开头并以逗号结尾(结果包含逗号)?





示例字符串:

dd301 / 122/4454,dd300 / 122/300,NR45,



预期成果:

dd300 / 122/300,



我的尝试:



可以获得以下匹配dd300,但需要知道如何包含正斜杠并停在逗号处。



(?<!\w)dd300

How do I find the string with a Regular Expression in the example below that start with 'dd300' and end with a comma (result to include the comma)?


Example string:
dd301/122/4454,dd300/122/300,NR45,

Expected Result:
dd300/122/300,

What I have tried:

Can get the following to match dd300, but need to know how to include forward slashes and stop at the comma.

(?<!\w)dd300

推荐答案

像斜线一样的特殊字符必须用反斜杠转义。



要匹配特定字符,请使用。* 。+ 后跟该字符。因为那些贪心(这个术语应该由每个正则表达式tuturioal处理),附加一个



所以最终的正则表达式可能是:

Special characters like the slash must be escaped with a back slash.

To match until a specific character occurs use .* or .+ follwed by that character. Because those are greedy (the term should be handled by every regex tuturioal), append a ?.

So the final regex might be:
(dd300\/.+?,)

括号只是当你需要访问匹配的字符串时需要。



根据你的输入,你也可以使用更具体的正则表达式。例如,如果 dd300 总是以两个斜线分隔的数字表示,则可以是

The parentheses are only necessary when you need to access the matched string.

Depending on your input you may also use a more specific regex. If for example the dd300 is always follwed by two slash separated numbers it can be

(dd300\/\d+\/\d+,)

其中 \d 指定与使用相同的任何数字[0-9]


最基本的就是:
dd300.*?,

哪个是''dd300';后跟任何字符,任意数量的重复,尽可能少;然后是逗号。



如果你要去使用正则表达式,然后获取 Expresso 的副本[ ^ ] - 它是免费的,它会检查并生成正则表达式。

Which is "'dd300'; followed by any character, any number of repetitions, as few as possible; then a comma".

If you are going to work with regexes, then get a copy of Expresso[^] - it's free, and it examines and generates Regular expressions.


这篇关于使用带有正斜杠的正则表达式查找字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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