2016-11-30 121 views
1

我有这样的完整字符串 - “你好,你们所有人” 和我有一个像“全部” 坏字现在我设法找到第一个字符串中的第二个很容易, 但让我们说我的第一个字符串是“你好,你们所有人” 或“你好,我,你们” 甚至“你好,你们所有人” 有没有正则表达式的方式来找到它? 我已经得到了迄今试图找到字符串分隔符

String wordtocheck =pair.getKey().toString(); 
String newerstr = ""; 
for(int i=0;i<wordtocheck.length();i++) 
    newerstr+=wordtocheck.charAt(i)+"\\."; 
Pattern.compile("(?i)\\b(newerstr)(?=\\W)").matcher(currentText.toString()); 

但它不会做的伎俩 感谢所有帮助者

+1

难道还有'嗨A.L,L?你们? –

+0

是的,这是一个很好的观点,它可以是,甚至可以是“a.l l” – yanivtwin

回答

1

您可以动态插入\W*(=零个或多个非单词构建模式字符,也就是,要搜索字符不属于字母,数字或下划线)在一个关键字的字符之间为:

String s = "Hello a l l you guys"; 
String key = "all"; 
String pat = "(?i)\\b" + TextUtils.join("\\W*", key.split("")) + "\\b"; 
System.out.println("Pattern: " + pat); 
Matcher m = Pattern.compile(pat).matcher(s); 
if (m.find()) 
{ 
    System.out.println("Found: " + m.group()); 
} 

参见online demoString.join是用来代替TextUtils.join,因为这是一个Java演示)

如果可以在搜索词无字字符,你需要用(?<!\\S)(初始\b)和(?!\\S)(而不是尾随\b更换\b字边界),或完全删除。

+1

其他不好的词怎么样(全部就像一个例子),可以有多个词,然后你可以如何管理? –

+0

@mohanrathour:那种情况有什么问题?你试过了吗?看看[在线演示](https://ideone.com/QYYyX2),展示'你好吗? –

+0

我刚刚在正则表达式中添加了不区分大小写的嵌入式标志选项,因为它在OP中使用。 –

0

试试这个

String str="Hello .a-l l? guys"; 
    str=str.replaceAll("\\W",""); //replaces all non-words chars with empty string. 

STR现在“Helloallguys”

+0

但是,如果需要检查文本中找到的搜索字符串,则此方法无效。 –