Java 用于在字符串中查找两个单词的正则表达式
这是我的基本问题:我正在从文件中读取一些行。文件中每行的格式如下:Java 用于在字符串中查找两个单词的正则表达式,java,regex,Java,Regex,这是我的基本问题:我正在从文件中读取一些行。文件中每行的格式如下: John Doe 123 在Doe和123之间有一个选项卡 我正在寻找一个正则表达式,这样我就可以“挑选”约翰·多伊。类似于scanner.next(正则表达式)的东西会给我johndoe 这可能很简单,但我似乎无法让它工作。此外,我正在努力解决这个问题,而不必依赖于账单的存在 我在这里看过:。但这些答案都不起作用。我不断地遇到运行时错误 一些代码: while(inFile.hasNextLine()){ St
John Doe 123
在Doe
和123
之间有一个选项卡
我正在寻找一个正则表达式,这样我就可以“挑选”约翰·多伊。类似于scanner.next(正则表达式)
的东西会给我johndoe
这可能很简单,但我似乎无法让它工作。此外,我正在努力解决这个问题,而不必依赖于账单的存在
我在这里看过:。但这些答案都不起作用。我不断地遇到运行时错误
一些代码:
while(inFile.hasNextLine()){
String s = inFile.nextLine();
Scanner string = new Scanner(s);
System.out.println(s); // check to make sure I got the string
System.out.println(string.next("[A-Za-z]+ [A-Za-z]+")); //This
//doesn't work for me
System.out.println(string.next("\\b[A-Za-z ]+\\b"));//Nor does
//this
}
您需要为此使用正则表达式吗?您只需在每一行的
\t
上使用split
方法,只需抓取第一个或第二个元素(我不确定您所说的“拾取”john doe是什么意思) 如果您提供了正在尝试的代码,而这些代码会导致运行时错误,那么这会有所帮助
您可以使用正则表达式:
[A-Za-z]+ [A-Za-z]+
如果你一直知道你的名字会是两个字
你也可以试试
\b[A-Za-z ]+\b
匹配任意数量的单词(包含字母),确保它捕获整个单词(这就是“\b”的含义)-->返回“John Doe”而不是“John Doe”(后面还有空格)。不要忘记反斜杠需要在Java中转义。这基本上可以将John Doe与其他人隔离开来
public String isolateAndTrim( String candidate ) {
// This pattern isolates "John Doe" as a group...
Pattern pattern = Pattern.compile( "(\\w+\\s+\\w+)\\s+\\d*" );
Matcher matcher = pattern.matcher( candidate );
String clean = "";
if ( matcher.matches() ) {
clean = matcher.group( 1 );
// This replace all reduces away extraneous whitespace...
clean = clean.replaceAll( "\\s+", " " );
}
return clean;
}
分组括号将允许您从数字部分“选取”名称部分。“约翰·多伊”,“简·奥斯汀”,随便什么。您应该学习RegEx中的分组内容,因为它非常适合处理像这样的问题
删除多余空格的诀窍来自您喜欢简洁易读吗?如果是,请考虑下面的解决方案
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MyLineScanner
{
public static void readLine(String source_file) throws FileNotFoundException
{
File source = new File(source_file);
Scanner line_scanner = new Scanner(source);
while(line_scanner.hasNextLine())
{
String line = line_scanner.nextLine();
// check to make sure line is exists;
System.out.println(line);
// this work for me
Scanner words_scanner = new Scanner(line);
words_scanner.useDelimiter("\t");
while (words_scanner.hasNext())
{
System.out.format("word : %s %n", words_scanner.next());
}
}
}
public static void main(String[] args) throws FileNotFoundException
{
readLine("source.txt");
}
}
你有一些我们可以使用的代码吗?(John)。+(Doe)-一些人的可能重复,当遇到问题时,想想“我知道,我会使用正则表达式。”现在他们有两个问题。所以这两份工作我都找不到。第一个抛出异常,第二个只获取第一个或第二个单词(我不记得是哪个)。