简体   繁体   English

java 字符串正则表达式模式匹配和替换字符串

[英]java String regex pattern match and replace string

There is a string, if that pattern matches need to return first few char's only.有一个字符串,如果该模式匹配只需要返回前几个字符。

String str = "PM 17/PM 19 - Test String"; 

expecting return string --> PM 17期待返回字符串 --> PM 17

Here my String pattern checking for:这是我的字符串模式检查:

1) always starts with PM 1) 总是以PM开头
2) then followed by space (or some time zero space) 2)然后是空间(或某个时间零空间)
3) then followed by some number 3)然后是一些数字
4) then followed by slash (ie /) 4)然后是斜杠(即/)
5) then followed by Same string PM 5) 然后是相同的字符串PM
6) then followed by space (or some time zero space) 6)然后是空间(或某个时间零空间)
7) Then followed by number 7) 然后是数字
8) then any other chars/strings. 8)然后是任何其他字符/字符串。

If given string matches above pattern, I need to get string till before the slash (ie PM 17 )如果给定的字符串与上述模式匹配,我需要在斜杠之前获取字符串(即PM 17

I tried below way but it did not works for the condition.我尝试了以下方式,但不适用于这种情况。

  if(str.matches("PM\\s+[0-9.]/PM(.*)")) { //"PM//s+[0-9]/PM(.*)"
                  str = str.substring(0, str.indexOf("/"));
                  flag = true;
  } 

Instead of .matches you may use .replaceFirst here with a capturing group :而不是.matches您可以在此处使用.replaceFirst捕获组

str = str.replaceFirst( "^(PM\\s*\\d+)/PM\\s*\\d+.*$", "$1" );
//=> PM 17

RegEx Demo正则表达式演示

RegEx Details:正则表达式详细信息:

  • ^ : Line start ^ : 行开始
  • (PM\\s*\\d+) : Match and group text starting with PM followed by 0 or more whitespace followed by 1 or more digits (PM\\s*\\d+) :匹配和分组以PM开头的文本,后跟 0 个或多个空格,后跟 1 个或多个数字
  • /PM\\s*\\d+ : Match /PM followed by 0 or more whitespace followed by 1 or more digits /PM\\s*\\d+ :匹配/PM后跟 0 个或多个空格,后跟 1 个或多个数字
  • .*$ : Match any # of characters before line end .*$ :匹配行尾之前的任意字符数
  • $1 : is replacement that puts captured string of first group back in the replacement. $1 :是替换,将捕获的第一组字符串放回替换中。

If you want to do input validation before substring extraction then I suggest this code:如果您想在 substring 提取之前进行输入验证,那么我建议使用以下代码:

final String regex = "(PM\\s*\\d+)/PM\\s*\\d+.*";    
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(str);

if (matcher.matches()) {
    flag = true;
    str = matcher.group(1);
}

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

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