在Java中使用正则表达式进行匹配?
我希望在文本字符串中找到整个单词。字符串中的单词由空格和新行分隔,因此我使用这两个字符来查找每个单词的开头和结尾。当模式为\s或\n时,程序将正确查找索引,而在匹配两个字符时则不会。如何修复此程序在Java中使用正则表达式进行匹配?,java,regex,Java,Regex,我希望在文本字符串中找到整个单词。字符串中的单词由空格和新行分隔,因此我使用这两个字符来查找每个单词的开头和结尾。当模式为\s或\n时,程序将正确查找索引,而在匹配两个字符时则不会。如何修复此程序 import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class convertText{ public static String findText(Stri
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class convertText{
public static String findText(String text){
String r = text.trim();
// System.out.println(r);
Pattern pattern = Pattern.compile("\\s+ | \\n");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
// System.out.println(matcher.start());
System.out.println(text.substring(matcher.start()+1));
}
return text;
}
public static void main(String[] args) {
// String test = " hi \n ok this. ";
String test = " hi ok this. ";
// System.out.println(test.substring(7));
// System.out.println(test);
findText(test);
}
}
您可以使用[^\\s]+搜索任何不是换行符或空格(又称单词)的字符,并打印组:
Pattern pattern = Pattern.compile("[^\\s]+");
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
System.out.println(matcher.group());
}
[^\\s]+可分为:
\\s匹配任何空白字符,这包括常规空格和换行符,因此不需要单独指定\\n
[和]定义了一个。这将匹配括号内的任何字符
^表示不匹配,因为字符集中的第一个字符反转匹配,并且只匹配集合中的字符,在本例中,除了空格和换行符之外,其他字符都不匹配。
+匹配一个或多个上一个标记,在本例中,上一个标记是匹配非空白字符的字符表达式
您可以使用Java8流API实现它,如下所示
String test = " hi ok this. ";
Pattern.compile("\\W+").splitAsStream(test.trim())
.forEach(System.out::println);
输出:
如果要匹配文本字符串中的所有单词,可以使用: ?i[a-z]+java转义:?i[a-z]+ ?我。。。启用不区分大小写的匹配。 [a-z]+。。。尽可能多地匹配来自a-z的任何字母 或者您可以使用: \w+。。。匹配ASCII字母、数字和下划线。尽可能多次
\s不匹配单个空格。它匹配ASCII空格、制表符、换行符、回车符、垂直制表符和换行符。因此,只需\s+即可匹配所有类型的空白字符。只需按空白字符集拆分字符串:
String[] words = yourString.split("\\s+");
你在找这个吗:?不。。。它找不到的索引o@Pippi你只是想抓住这些话吗?
try {
String subjectString = " hi ok this. ";
Pattern regex = Pattern.compile("(?i)[a-z]+", Pattern.MULTILINE);
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
String word = regexMatcher.group();
int start_pos = regexMatcher.start();
int end_pos = regexMatcher.end();
JOptionPane.showMessageDialog(null, ""+word+ " found from pos: "+start_pos+" to "+end_pos);
}
} catch (PatternSyntaxException ex) {
}
String[] words = yourString.split("\\s+");