简体   繁体   English

在字符串中查找正则表达式模式

[英]Find a Regex Pattern in a String

I'm trying to print out a pattern from a string. 我正在尝试从字符串中打印出图案。

String stringToProcess = "Test Test Hello World Test Test";
String pattern = "Hello\\sWorld";
System.out.println(stringToProcess.substring(stringToProcess.indexOf(pattern), stringToProcess.lastIndexOf(pattern)));

When I run this code it seems to give lots of errors depending on how I try to change it and repair it. 当我运行此代码时,根据我尝试对其进行更改和修复的方式,似乎会出现很多错误。 As it is above, it gives the error: 如上所述,它给出了错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

Please note: I already am aware of the Pattern.compile(regex, Pattern); 请注意:我已经知道Pattern.compile(regex, Pattern); way of doing this. 这样的方式。 I would like to do it in a different way. 我想以其他方式来做。

Here is your requested example: 这是您要求的示例:

    String stringToProcess = "Test Test Hello World Test Test";
    String patternString = "Hello\\sWorld";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(stringToProcess);
    if (matcher.find()) {
        int start = matcher.start();
        int end = matcher.end();
        System.out.println(stringToProcess.substring(start, end));
    }

Beacause you really wanted to use \\\\s instead of a blank, it will also match Hello\\tWorld , Hello\\nWorld and all other possible single whitespace character between Hello and World. 东阳你真的想用\\\\s而不是一片空白,这也将匹配Hello\\tWorldHello\\nWorld和你好与世界之间的所有其他可能的单个空格字符。

The way I have it written it will only print the first found match (if there is one), if you want of print all matches to your pattern replace if with while . 我写的方式只会打印找到的第一个匹配项(如果有),如果您想将所有匹配项打印到您的模式中, ifwhile替换。

But I wouldn't use start() , end() and substring() if I didn't have to, you can just print matcher.group() if you want to print your match. 但是如果不需要,我不会使用start()end()substring() ,如果要打印匹配项,可以只打印matcher.group()

This is function that return the start location of the sentence : 这个函数返回句子的开始位置:

public  static int decodeString(String msg,String sentence) {
        Pattern p = Pattern.compile("(.*)"+sentence+"(.*)");
        Matcher m = p.matcher(msg);
        if (m.matches()) {
           return  m.end(1);
        }
        return -1;
    }

Note that this give the last matching. 请注意,这给出了最后一个匹配项。 If we have some matches we need to work with loop 如果我们有一些匹配项,我们需要使用循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM