1

i dont know much about regular expressions and from what i'v learned i cant solve my entire problem.

I have this String:

04 credits between subjects of block 02

I'm only sure i will have [00-99] on the beggining and at end.

I wanna capture the beggining and the end IF the middle has "credits between", the system can have other formats as input, so i wanna be sure that these fields captured will go from the correct pattern.

This is what i'v tried to do:

(\w\w) ^credits between$.+ (\w\w)

I'm using the Regexr website to see what i'm doing, but no success.

PlayMa256
  • 5,711
  • 1
  • 24
  • 46
  • You can use `^\d{2} .*?credit between.*? \d{2}$` – anubhava Oct 21 '15 at 14:23
  • The hyphen in a character class is used to define a range of characters (take a look at the ascii table) and not a range of integers. `[00-99]` is exactly the same than `[0-9]`, `[00-9]`, `[0-99]`, `[0123456789]`, `[2587410369]`, `[1-405-89]` ... and matches only one character (included in the character set). – Casimir et Hippolyte Oct 21 '15 at 14:32

1 Answers1

2

You may use the following regex:

^(\d{2})\b.*credits between.*\b(\d{2})$

See regex demo

It will match and capture 2 digits at the beginning and end if the string itself contains credits between. Note that newlines can be supported with [\s\S] instead of ..

The word boundaries \b just make the engine match the digits followed by a non-word character (you may remove it if that is not expected behavior). Then, you'd need to use ^(\d{2})\b.*credits between.*?(\d{2})$ with the lazy matching .*? at the end.

If the number of digits in the numbers at both ends can vary, just use

^(\d+).*credits between.*?(\d+)$

See another demo

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • Please precise the programming language you are using. – Wiktor Stribiżew Oct 21 '15 at 14:25
  • it's java, i managed to validate the string that i'm recieving and capture the groups i want with yout regex. Thanks. Theres any good tutorial o could learn more about it? – PlayMa256 Oct 22 '15 at 13:10
  • In Java, you'd need to use my regex like this: `if (str.matches("(\\d{2})\\b.*credits between.*\\b(\\d{2})")) { ... }`. I do not know your level of regex knowledge :) so that I can only suggest doing all lessons at [regexone.com](http://regexone.com/), reading through [regular-expressions.info](http://www.regular-expressions.info), [regex SO tag description](http://stackoverflow.com/tags/regex/info) (with many other links to great online resources), and the community SO post called [What does the regex mean](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean). – Wiktor Stribiżew Oct 22 '15 at 13:22