开发者

regular expressions - finding the position of a number and removing brackets around it

I'm stuck. I tried it with regular expressions, but I guess I'm missing something. I'm working with JavaScript.

I have an input like:

(text [开发者_开发百科number]) the text that follows...

I want an output like:

[number] the text that follows...

I tried it with substr, but my problem is that I do not know the length of the text or number in the brackets. I guess I need the position of the beginning and ending of the number to work with a regEx.

Have you got an idea?


Regexes are the way to go — using JavaScript’s replace function, you don’t need to fiddle with the position of the number in the string.

Try this:

var geoff = '(text 694) the text that follows...';
var geoff_replaced = geoff.replace(/\([^0-9]* ([0-9]*)\)/, '$1');

# geoff_replaced will be "694 the text that follows...

I don’t do much JavaScript regex stuff, so I totally looked up the above on this guide to JavaScript regexes:

  • http://www.evolt.org/node/36435


It'd help to have a real example but I made one up...

Text:

(Some text 1234) some more text.

Regex:

^.+?(?<Number>\d+)\)(?<Text>.+)$

Replacement:

${Number}${Text}

Full example:

var fixedText = "(Some text 1234) some more text.".replace(/^.+?(?<Number>\d+)\)(?<Text>.+)$/, "${Number}${Text}");


the regex that matches (text [number]) the text that follows... can be like:

"^\(.*?([0-9]*)\)(.*)$"

or you can just match the beginning (and the ending )) and remove it

"^(\(.*?)[0-9]*(\)).*$"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜