简体   繁体   中英

Using regex get particular value

I have a response like below

2020 Aug 05 09:31:25.646515 arrisxg1v4 WPEWebProcess[22024]: [AAMP-PLAYER]NotifyBitRateChangeEvent :: bitrate:2800000 desc:BitrateChanged - Network adaptation width:1280 height:720 fps:25.000000 position:256.000000

From this using regex how I can retrieve position value only as Integer. Using java code I can get it using.split method But How I can get this value 256 using Regex?

Try this one-liner:

String positionStr = str.replaceAll("(?:(?!position:).)*(?:position:(\\d+))?.*", "$1");
Integer position = positionStr.isEmpty() ? null : new Integer(positionStr);

This regex matches the whole string, capturing the target position value in group 1 ( (?:...) is a non-capturing group), and replaces the match (ie everything) with the captured group. This effectively deletes everything you don't want.

Conveniently, because the capture is optional (has a quantifier of ? ), if the input does not have a position: value, the result is a blank string.

The negative lookahead (?:position.). prevents the dot running past our target. Without the negative lookahead, the first dot would consume the entire input.

You could try something like this:

Pattern pattern = Pattern.compile(".*position:(\\d+(\\.\\d+))");
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
   String position = matcher.group(1);
}

Basically what this expression says is:

  • Accept anything up until the word position
  • Accept a colon :
  • Accept 1 or more digits (0-9), optionally followed by a dot and 1 or more digits

Then by using matcher.group you take everything between parentheses starting at the 1st parenthesis from the left.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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