Reputation: 4496
This is a sample text i'm running my regex on:
DuraFlexHose Water 1/2" hex 300mm 30.00
I want to include everything and stop at the 30.00
So what I have in mind is something like [^\d*\.\d*]*
but that's not working. What is the query that would help me acheive this?
Upvotes: 1
Views: 51
Reputation: 626738
If you cannot use any CSV parser and are only limited to regex, I'd suggest 2 regexps.
This one can be used to grab every character from the beginning up to the first pattern of optional spaces
+ digits(s)
+ .
+ digit(s)
:
^([\s\S]*?)\s*\d+\.\d+
See demo
In case the float value is at the end of string, use a $
anchor (the end of string):
^([\s\S]*?)\s*\d+\.\d+$
See another demo
Note that [\s\S]
matches any symbol, even a newline.
Regex breakdown:
^
- Start of string([\s\S]*?)
- (Capture group 1) any symbols, 0 or more, as few as possible otherwise, 3
from 30.45
will be captured)\s*
- 0 or more whitespace, as many as possible (so as to trim Group 1)\d+\.\d+
- 1 or more digits followed by a period followed by 1 or more digits$
- end of string.If you plan to match any floats, like -.05
, you will need to replace \d+\.\d+
with [+-]?\d*\.?\d+
.
Here is how it can be used:
var str = 'DuraFlexHose Water 1/2" hex 300mm 300.00';
var res = str.match(/^([\s\S]*?)\s*\d+\.\d+/);
if (res !== null) {
document.write(res[1]);
}
Upvotes: 1
Reputation: 1212
See Demo
/.*(?=\d{2}\.\d{2})/
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
(?=\d{2}\.\d{2}) Positive Lookahead - Assert that the regex below can be matched
\d{2} match a digit [0-9]
Quantifier: {2} Exactly 2 times
\. matches the character . literally
\d{2} match a digit [0-9]
Quantifier: {2} Exactly 2 times
Upvotes: 1