在Java中从字符串中提取模式

在Java中从字符串中提取模式,java,pattern-matching,Java,Pattern Matching,我在Java中有一个字符串变量,如下所示 String s = "hello\nthis is java programme\n.class file will be generated after executing it\n"; 现在我需要从上面的字符串变量中提取.class部分。如何做到这一点?我真的只看到一种方法,让您不只是简单地输出“.class”,即在打印之前先查看字符串是否包含“.class”。 这里有一个这样做的函数。传递要查找的字符串和要搜索的字符串 //Returns th

我在Java中有一个
字符串
变量,如下所示

String s = "hello\nthis is java programme\n.class file will be generated after executing it\n";

现在我需要从上面的字符串变量中提取
.class
部分。如何做到这一点?

我真的只看到一种方法,让您不只是简单地输出“.class”,即在打印之前先查看字符串是否包含“.class”。 这里有一个这样做的函数。传递要查找的字符串和要搜索的字符串

//Returns the string if found, else returns an empty string
public String FindString(String whatToFind, String whereToFind)
{
    return whereToFind.contains(whatToFind) ? whatToFind : "";
}
输出

String s = "hello\nthis is java programme\n.class file will be generated after executing it\n";
System.out.println(FindString(".class", s)); // prints .class

如果您只想检查字符串中是否有“.class”模式,您可以很容易地进行如下检查:

s.contains(".class");
或者,如果需要,请使用正则表达式检查包含
\n
的字符串中是否存在类似
.class
的模式:

Pattern p = Pattern.compile(".*\\.class.*", Pattern.DOTALL);
Matcher m = p.matcher(s);
boolean b = m.matches();
DOTALL
启用也被视为字符的
\n


s是您在代码中定义的字符串。

使用正则表达式,如下所示

String s=“您好\n这是java程序\n.class文件将在执行后生成\n”;
//我想下面的模式会找到你想要的,
Pattern=Pattern.compile(“\n(.\.class)”);
匹配器匹配器=模式匹配器;
if(matcher.find())
{
系统输出println(匹配器组(1));
}

如果您只需要
.class
,那么只需使用
“.class”
。我想你还想要别的?你能更精确地定义它吗?显示您的输出字符串应该是什么?我建议使用正则表达式,但我不了解您的要求。
.class
部分是什么?如果它只是文字,那么“提取”是什么意思?它只是我试图从字符串中提取的一种模式。输出应该是什么样子的?是否希望所有内容都符合.class的要求?下课后?什么?人们真的很想帮助你,但正如评论所示,你的问题并不清楚。我将尝试重申我认为您在问的问题:我有一个
String
变量,它在Java中具有以下结构。String s=“hello\n这是java程序\n.class文件将在执行后生成\n”;现在我需要从上面的字符串变量中提取
.class
部分,这样我就有了一个只包含字符串的class和.class部分的变量。如何仅提取字符串的类名和.class位?
String s = "hello\nthis is java programme\n<some_class_name_here>.class file will be generated after executing it\n";
//the following pattern I think will find what you're looking for,
Pattern pattern = Pattern.compile("\n(.*\.class)");
Matcher matcher = pattern.matcher(s);
if (matcher.find())
{
    System.out.println(matcher.group(1));
}