使用正则表达式的字符串查找确切的字符 [英] Find exact characters in string using regex

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

问题描述

我有以下



类似字符串

  M10结束
开始M11
M1
M1启动
M N1
端M1

我想实现的就是让只有有结果的 M1 使用正则表达式。



这是我当前的代码

 正则表达式R =新的正则表达式(^ $ M1 | M1 $); 



输出看起来像下面一个缺少字符串M1开始

  M1 
端M1


解决方案

 正则表达式R =新的正则表达式(^ * \\bM1\\b * $); 

这应该u太强势demo.Here \b <做/ code>是单词边界,这将只匹配 M1 ,而不是 M10




\b在单词边界断言位置(^ \w | \w $ | \W\w | \w\W)




https://regex101.com / R / sJ9gM7 / 113


I have strings like below

M10 end 
start M11
M1
M1 start
M n1
end M1

What I am trying to achieve is get the result having only "M1" using regex.

This is my current code

Regex r = new Regex("^M1$|M1$");

The output looks like below which is missing string "M1 start"

M1
end M1

解决方案

Regex r = new Regex("^.*\\bM1\\b.*$");

This should do it for you.See demo.Here \b is word boundary which will match only M1 and not M10.

\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)

https://regex101.com/r/sJ9gM7/113

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

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