RegEx: Separating a String in two at the $
I have a string that I import into my javascri开发者_如何转开发pt application. It consists of this:
Text here (some text in parenthesis) $Price
I would like to separate this string into three strings (The beginning part, the parenthesis, and the price).
I know this probably involves regular expressions, but that is a beast I cannot hope to tackle right now. Does anyone have any suggestions?
Thanks!
Without regular expressions, this works:
var part1 = mystring.substring(0, mystring.indexOf('('));
var part2 = mystring.substring(mystring.indexOf('(') + 1, mystring.indexOf(')'));
var part3 = '$' + mystring.split('$')[1];
Example/demo: http://jsfiddle.net/fallen888/6EU3W/3/
Update:
var part1 = null;
var part2 = null;
var part3 = null;
if (mystring.indexOf('(') >= 0 && mystring.indexOf('(') > 0) {
part1 = mystring.substring(0, mystring.indexOf('('));
part2 = mystring.substring(mystring.indexOf('(') + 1, mystring.indexOf(')'));
part3 = '$' + mystring.split('$')[1];
}
else {
var parts = mystring.split('$');
part1 = parts[0];
part2 = '$' + parts[1];
}
var str = "Text here (some text in parenthesis) $33.55";
var matches = str.match(/(.+) (\(.+\)) (\$.+)/);
Gives you:
["Text here (some text in parenthesis) $33.55", "Text here", "(some text in parenthesis)", "$33.55"]
matches[1]
, matches[2]
, and matches[3]
contain what you want.
var match = "Text here (some text in parenthesis) $Price".match(/(.+)(\(.+\))(.+)/);
match[1], match[2], match[3];
Or using split
(see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split):
var split12 = "Text here (some text in parenthesis) $Price".split('(');
var split1 = split12[0];
var split23 = split12[1].split(')');
var split2 = '(' + split23[0] + ')';
var split3 = split23[1];
Better to learn some regexp, don't you think?
http://jsfiddle.net/K9Cxe/
Try this:
([\w\s]+) (([\w\s]+)) (\$\w+)
Assuming that when you say text, it is alpahnumeric. If you want to allow punctuation marks, modify [\w\s]
to include those as well. (e.g. to include comma -> [\w\s,]
).
精彩评论