繁体   English   中英

如何使用正则表达式仅匹配字符串中特定位置的模式?

[英]How can I use a regex to match a pattern only at a specific position in the string?

假设4个字符串,2个匹配,另一个不匹配:

String string1 = "Hello World View";
String string2 = "Hello Nether World";
String string3 = "A World You should not find";
String string4 = "Any   World is good";

什么正则表达式只匹配string1string4 ,其中World6位开始?

"^.{6}World"

假设您正在使用不需要整个字符串匹配的Matcher.find^表示“字符串的开头”,因此这需要字符串的开头后跟任意六个字符,然后是您的模式。

你可以使用积极的lookbehind断言

(?<=^.{6})World
String.matches(".{6}World.*")

一开始,6个字符,世界

没有正则表达式,substr会更快。

伪代码:

String strWorld = "World";  
String string1 = "Hello World View";  
bool bFound = false;
bFound = ( strWorld == string1.substr(6, strWorld.length()) ) ? true : false;
if ( bFound ) { }  

您可以使用方法region()来搜索字符串的一部分。 我的情况:

matcher.region(6, str.length());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM