The results I want:
T1 T3 T5 T8 "
= no match since the quote is incomplete or even better, match characters before the quote T1 T3 T5 T8 "T4
= match T1 T3 T5, ignore T4 = not a requirement but would be nice if this can be achieved as well T1 T3 T5 T8 "T9"
= match only T1 T3 T5 T8, ignore T9 O2 T3 O5 "T7 T9" O8
= match O2 T3 O5 O8, ignore matches within the quote This is the regex I have so far, but I can't make it mismatch everything if the quote is incomplete.
/(^|\b)(t|o)\d+(?=([^"]*"[^"]*")[^"]*$)/gi
You could go for a two step validation:
a = YourString
a.match(/\"[^\"]+\"/) ? a.replace(/([^\"]*)\".*\"([^\"]*)/,"$1$2") : ""
a='T1 T3 T5 T8 "'
# ""
a='O2 T3 O5 "T7 T9" O8'
# "O2 T3 O5 O8"
a='T1 T3 T5 T8 "T9"'
# "T1 T3 T5 T8 "
UPDATE
To cover the not required case, just add another condition
a.match(/\"[^\"]+\"/) ? a.replace(/([^\"]*)\".*\"([^\"]*)/,"$1$2") : a.replace(/([^\"]*)\"[^\"]*/,"$1")
for what you posted use this pattern
"[^"\r\n]*"|"[^"\r\n]*$|(\w+)
and check against sub-pattern #1
Demo
You can just do a replace
and then a conditional split
:
// case 1
var str = 'O2 T3 O5 "T7 T9" O8';
var r = str.replace(/\s*"[^"]*"/g, '');
var m;
if (str != r)
m = r.split(/\s+/);
console.log(m);
//=> ["O2", "T3", "O5", "O8"]
// Case 2
var str = 'O2 T3 O5 "';
var r = str.replace(/\s*"[^"]*"/g, '');
var m;
if (str != r)
m = r.split(/\s+/);
console.log(m);
//=> undefined
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.