Home > Mobile >  How to retrieve the targeted substring, if the number of characters can vary?
How to retrieve the targeted substring, if the number of characters can vary?

Time:06-10

I want to retrieve from input similar to the following: code="XY85XXXX", the substring between "".
In case of a fixed number of 8 characters I can retrieve the value with (?<=code=").{8}. But the targeted substring length varies, 7 or 9, or somewhere in the range between 3 and 11 (as in the examples below) and that is what I need to also handle.
Input can for example be code="XY85XXXX765" or code="123".

How must I adjust the regex to achieve that flexibility?

CodePudding user response:

You can use a lookahead and lookbehind both searching for quotes:

(?<=").*(?=")

let rx = /(?<=").*(?=")/;
let extract = (txt) => console.log(txt.match(rx)[0]);

extract('code="XY85XXXX"');
extract('code="Y85XXXX"');
extract('code="ZXY85XXXXZ"');

CodePudding user response:

Thanks for the answer. Yes, indeed that is. I found something easily -> (?<=code=").*\s It is because it is just a part of a whole string.

Sorry for my question, I know it is not clear because I am ' gifted ' (hoogbegaafd - what a word, it is not a gift). and I sometimes think that everybody understands it.

CodePudding user response:

You can use positive lookbehind to 'anchor' your matches to the fixed part (?<=code=") and a negative character class allowing any character but " occurring one or more times:

(?<=code=")[^"] 
  • Related