简体   繁体   English

正则表达式与特殊字符组匹配

[英]Regexp matching in group with special characters

I have a String that is something like this: 我有一个像这样的字符串:

A20130122.0000+0000-0015+0000_name

Then I would like to extract this information: 然后,我想提取此信息:

The 20130122.0000+0000-0015+0000 that will be parsed to a date later on. 20130122.0000+0000-0015+0000 ,将在以后解析为一个日期。 And the final part which is name . 最后一部分是name

So I am using in Java something like this: 所以我在Java中使用这样的东西:

String regexpOfdate = "[0-9]{8}\\.[0-9]{4}\\+[0-9]{4}-[0-9]{4}\\+[0-9]{4}";
String regexpOfName = "\\w+";
Pattern p = Pattern.compile(String.format("A(%s)_(%s)", regexpOfdate, regexpOfName));
Matcher m = p.matcher(theString);
String date = m.group(0);
String name = m.group(1);

But I am getting a java.lang.IllegalStateException: No match found 但我收到java.lang.IllegalStateException: No match found

Do you know what I am doing wrong? 你知道我在做什么错吗?

You aren't calling Matcher#find or Matcher#matches methods after this line: 您不会在此行之后调用Matcher#findMatcher#matches方法:

Matcher m = p.matcher(theString);

Try this code: 试试这个代码:

Matcher m = p.matcher(theString);
if (m.find()) {
    String date = m.group(1);
    String name = m.group(2);
    System.out.println("Date: " + date + ", name: " + name);
}

Matcher#group will throw IllegalStateException if the matcher's regex hasn't yet been applied to its target text, or if the previous application was not successful. 如果尚未将匹配器的正则表达式应用于其目标文本,或者如果先前的应用程序未成功,则Matcher#group将引发IllegalStateException

Matcher#find applies the matcher's regex to the current region of the matcher's target text, returning a Boolean indicating whether a match is found. Matcher#find将匹配器的正则表达式应用于匹配器目标文本的当前区域,并返回一个布尔值,指示是否找到匹配项。

Refer 参考

You can try this : 您可以尝试以下方法:

    String theString="A20130122.0000+0000-0015+0000_name";
    String regexpOfdate = "([0-9]{8})\\.[0-9]{4}\\+[0-9]{4}-[0-9]{4}\\+[0-9]{4}";
    String regexpOfName = "(\\w+)";
    Pattern p = Pattern.compile(String.format("A(%s)_(%s)", regexpOfdate, regexpOfName));
    Matcher m = p.matcher(theString);
    if(m.find()){
      String date = m.group(2);
      String name = m.group(3);
      System.out.println("date: "+date);
      System.out.println("name: "+name);
    }

OUTPUT OUTPUT

date: 20130122
name: name

Refer Grouping in REGEX 请参考REGEX中的分组

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

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