简体   繁体   中英

Regex trying to match characters before and after symbol

I'm trying to match characters before and after a symbol, in a string.

string: budgets-closed

To match the characters before the sign - , I do: ^[az]+

And to match the other characters, I try: \\-(\\w+) but, the problem is that my result is: -closed instead of closed .

Any ideas, how to fix it?

Update

This is the piece of code, where I was trying to apply the regex http://jsfiddle.net/trDFh/1/

I repeat: It's not that I don't want to use split; it's just I was really curious, and wanted to see, how can it be done the regex way. Hacking into things spirit

Update2

Well, using substring is a solution as well: http://jsfiddle.net/trDFh/2/ and is the one I chosed to use, since the if in question, is actually an else if in a more complex if syntax, and the chosen solutions seems to be the most fitted for now.

Use exec() :

var result=/([^-]+)-([^-]+)/.exec(string);

result is an array, with result[1] being the first captured string and result[2] being the second captured string.

Live demo: http://jsfiddle.net/Pqntk/

I think you'll have to match that. You can use grouping to get what you need, though.

var str = 'budgets-closed';
var matches = str.match( /([a-z]+)-([a-z]+)/ );

var before = matches[1];
var after = matches[2];

For that specific string, you could also use

var str = 'budgets-closed';
var before = str.match( /^\b[a-z]+/ )[0];
var after = str.match( /\b[a-z]+$/ )[0];

I'm sure there are better ways, but the above methods do work.

If the symbol is specifically - , then this should work:

\b([^-]+)-([^-]+)\b

You match a boundry, any "not - " characters, a - and then more "not - " characters until the next word boundry.

Also, there is no need to escape a hyphen, it only holds special properties when between two other characters inside a character class.

edit: And here is a jsfiddle that demonstrates it does work .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM