Reputation: 47
I have string in this format:
var a="input_[2][invoiceNO]";
I want to extract "invoiceNo" string. I've tried:
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]');
var res = patt.exec(a);
However, I get the following output:
Array [ "[2]", "2" ]
I want to extract only invoiceNo
from the string.
Note: Input start can be any string and in place of number 2
it can be any number.
Upvotes: 1
Views: 60
Reputation: 626689
I would check if the [...]
before the necessary [InvoiceNo]
contains digits and is preceded with _
with this regex:
/_\[\d+\]\s*\[([^\]]+)\]/g
Explanation:
_
- Match underscore\[\d+\]
- Match [1234]
-like substring\s*
- Optional spaces\[([^\]]+)\]
- The [some_invoice_123]
-like substringYou can even use this regex to find invoice numbers inside larger texts.
The value is in capture group 1 (see m[1]
below).
Sample code:
var re = /_\[\d+\]\s*\[([^\]]+)\]/g;
var str = 'input_[2][invoiceNO]';
while ((m = re.exec(str)) !== null) {
alert(m[1]);
}
Upvotes: 2
Reputation: 174696
Use the greediness of .*
var a="input_[2][invoiceNO]";
var patt = new RegExp('.*\[(.*?)\]');
var res = patt.exec(a);
Upvotes: 0
Reputation: 52185
You could use something like so: \[([^[]+)\]$
. This will extract the content within the last set of brackets. Example available here.
Upvotes: 0
Reputation: 9420
Try this:
var a="input_[2][invoiceNO]";
var patt = new RegExp(/\]\[(.*)\]/);
var res = patt.exec(a)[1];
console.log(res);
Output:
invoiceNO
Upvotes: 0
Reputation: 67968
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]$');
var res = patt.exec(a);
Upvotes: 0
Reputation: 784898
You can use this regex:
/\[(\w{2,})\]/
and grab captured group #1 from resulting array of String.match
function.
var str = 'input_[2][invoiceNO]'
var m = str.match(/\[(\w{2,})\]/);
//=> ["[invoiceNO]", "invoiceNO"]
PS: You can also use negative lookahead to grab same string:
var m = str.match(/\[(\w+)\](?!\[)/);
Upvotes: 0