您好我正在寻找正则表达式来匹配一个字符串,使其不以字母或数字开头或结尾,或者_下划线。
我试过以下但似乎没有用。
public class Test {
public static final String EXAMPLE_TEST = "This is my MyText example string which I'm going to use for pattern matching.";
public static void main(String[] args) {
Pattern pattern = Pattern.compile("(\\W*)(\\D*)" + "MyText" + "(\\W*)(\\D*)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(EXAMPLE_TEST);
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end() + " ");
}
}
}
我试过以下但似乎没有用。
Desired o/p = 5
Current Result = 0
示例代码:
public class Test {
public static final String EXAMPLE_TEST = "#myText myTExT myText!@ Test nmyText myText test";
public static void main(String[] args) {
String[] array = EXAMPLE_TEST.split(" ");
int count = 0;
for(String line : array){
Pattern pattern = Pattern.compile("(?<=\\W)MyText(?=\\W)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
count++;
}
}
System.out.println(count);
}
}
如果我使用单个字符串作为
public static final String EXAMPLE_TEST = "#myText myTExT myText!@ Test nmyText myText test";
使用while语句我希望o / p为5。
while(matcher.find()){
count++;
}
System.out.println(count);
在这种情况下,输出为预期的5。
答案 0 :(得分:2)
匹配一个字符串,使其不以字母或数字开头或结尾,或_Underscore。
您可以尝试使用Positive Lookaround
(?<=\W)MyText(?=\W)
您可以在上面的正则表达式
中使用[^\w]
代替\W
\W
匹配任何非单词字符[^a-zA-Z0-9_]
\w
匹配任何字词[a-zA-Z0-9_]
根据评论
String EXAMPLE_TEST = "It fails for following text #myText myTExT myText!@ Test myText myText test.";
Pattern pattern = Pattern.compile("(?<=\\W)MyText(?=\\W)",
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(EXAMPLE_TEST);
while (matcher.find()) { // <--- Look Here, use while instead of if
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end() + " ");
System.out.println(" Match String: " + matcher.group() + " ");
}
输出:
Start index: 29 End index: 35 Match String: myText
Start index: 36 End index: 42 Match String: myTExT
Start index: 43 End index: 49 Match String: myText
Start index: 57 End index: 63 Match String: myText
Start index: 64 End index: 70 Match String: myText
OP在原帖中有很多编辑
如果您正在进行拆分,那么在这种情况下它将成为一个单词
Pattern.compile("(?<=\\W|^)MyText(?=\\W|$)", Pattern.CASE_INSENSITIVE);
答案 1 :(得分:2)
我正在搜索MyText,但MyText不应该以任何其他字母或数字开头或_,允许使用空格和其他符号
对我来说,看起来简单的单词边界将起作用,即这个正则表达式:
\bMyText\b
答案 2 :(得分:0)