我有以下代码来对字符串执行一些正则表达式
public class RegexForPresto {
public static void main(String[] args) {
Pattern p = Pattern.compile("^M^M rawtostampedMsg^L 48^UT ");
String candidateString = "^M^M rawtostampedMsg^L 48^UT 1338802566.906^EOH^name;
Matcher matcher = p.matcher(candidateString);
String tmp = matcher.replaceAll("");
System.out.println(tmp);
}
}
而不是仅仅获取
^EOH^name
执行时得到以下输出
^M^M rawtostampedMsg^L 48^UT 1338802566.906^EOH^name
还可以从字符串中删除“^EOH^”,以便仅获得“name”作为输出。我不知道如何删除特殊字符(“^”)。如有任何帮助,我们将不胜感激。
提前致谢。
最佳答案
你可以使用这个模式
.*EOH.(.*)
然后从第一个捕获组获取结果,如下所示:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import junit.framework.Assert;
public class PatternTest {
@Test public void testPatter() {
Pattern p = Pattern.compile(".*EOH.(.*)");
String candidateString = "^M^M rawtostampedMsg^L 48^UT 1338802566.906^EOH^name";
Matcher matcher = p.matcher(candidateString);
if(matcher.matches()){
String tmp = matcher.group(1);
Assert.assertEquals("name", tmp);
}
}
}
关于java - java中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10880319/