简体   繁体   中英

Regex for number between special characters

I want to build a regex that will extract me numbers from a string. The pattern is

">number<"

Now the number can have decimals or not. I went with:

"[^\d]+"

This does extract the numbers but because of decimals, it sometimes works bad. Any ideas?

试试这个(用引号复制):

">[0-9]+(\.[0-9]+)?<"

A simple regex which works for integers, floats and negative numbers :

>([\+\-]?\d+\.?\d*)<

The number is in group 1.

If you can use positive lookarounds, this regex matches just a number between >< and nothing else :

(?<=>)[\+\-]?\d+\.?\d*(?=<)

Here in action.

>((\-|\+)?[0-9]+(\.[0-9]+)?)<

Explained:

  • (\\-|\\+)? optional sign: - or +
  • [0-9]+ - non-empty sequence of digits
  • (\\.[0-9]+)? - optional sequence starting with a dot followed by non-empty sequence of digits
  • > and < at the beginning and at the and (not in the matching group)

In the first matching group you will have your number.

Example here .

Assuming that it's just the number you want:

(?<=\\>)[0-9]+(\.[0-9]+)?(?=\<)

It matches any number with or without decimals between > and < but excluding > and <

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