Home > other >  Regex for getting integers and hyphen with spaces (special pattern recognition)
Regex for getting integers and hyphen with spaces (special pattern recognition)

Time:07-18

Here is the data I want to capture (10 - 12) <===== This format

Sample Data:

sdfdsfsdffsd 16.50sd - 57676766.0sd
16.50sd - 57676766.0sd
16.50sd - 57676766.0sd
sdfsdffsdf 6sd - 5.989898989sd sdfsdsdf
sdfdsf 6.50sd - 76.50sd sdfsdfsd
sdfsf sd 12sd - 15sd sdfdsdffsdff
16.50sd - 57sd
16sd - 50sd
1.50sd - 5.0sd
1sd - 5766.34sd the sdfdsfdsf spesdfdsfed
1sd - 5766.34sd the ssdfsdf  sdfsdf

Here is what I have so far for a regex

[^\w\.\n]((\s?\-?\s?)(\d*(?=\.)))

Here is the result: Link Here https://regex101.com/r/KNvHn8/1

So

  1. Required format (16 - 55)
  2. Sample Data blah blah 16.50 - 55.30 blah blah blah I need the Integers before the decimal points (16) ( - ) (55)

I can achieve this with 2 regex but preferable needs one.

Thanks

CodePudding user response:

If you only want the first digits before the dot and there has to be a hyphen in between, you can use 2 capture groups:

(\d )(?:\.\d )?[^\s\d-]*(\s-\s)[^\d-]*(\d )

Explanation

  • (\d ) Capture 1 digits in group 2
  • (?:\.\d )? Optionally match . and 1 digits
  • [^\s\d-]* Optionally match any char except a whitespace char, digit or -
  • (\s-\s) Capture - between whitespace chars in group 2
  • [^\d-]* Optionally match any char except - or a digit
  • (\d ) Capture 1 digits in group 3

See a regex demo

If you want the result on a line, you can use a replacement with the 3 groups:

^\D*(\d )(?:\.\d )?[^\s\d-]*(\s-\s)[^\d-]*(\d ).*

Example

String regex = "^\\D*(\\d )(?:\\.\\d )?[^\\s\\d-]*(\\s-\\s)[^\\d-]*(\\d ).*";
String string = "sdfdsfsdffsd 16.50sd - 57676766.0sd\n"
  "16.50sd - 57676766.0sd\n"
  "16.50sd - 57676766.0sd\n"
  "sdfsdffsdf 6sd - 5.989898989sd sdfsdsdf\n"
  "sdfdsf 6.50sd - 76.50sd sdfsdfsd\n"
  "sdfsf sd 12sd - 15sd sdfdsdffsdff\n"
  "16.50sd - 57sd\n"
  "16sd - 50sd\n"
  "1.50sd - 5.0sd\n"
  "1sd - 5766.34sd the sdfdsfdsf spesdfdsfed\n"
  "1sd - 5766.34sd the ssdfsdf  sdfsdf";
String subst = "$1$2$3";

Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(string);

System.out.println( matcher.replaceAll("$1$2$3"));

Output

16 - 57676766
16 - 57676766
16 - 57676766
6 - 5
6 - 76
12 - 15
16 - 57
16 - 50
1 - 5
1 - 5766
1 - 5766

See a Java demo

  • Related