Javascript RegEx:如何在单引号之间获取名称(不包括单引号)

时间:2016-04-14 07:22:02

标签: javascript regex

所以我有这个字符串

"Account(name=u'John Doe', firstName=None, accountNumber=None, middleName=None, lastName=None, blah=None, blah=None, blah=Identification(blah=u'None', blah=u'2016-02-29', blah=1, blah=u'2313', name=u'Passport'), blah=Address(address1=u'None', country=u'PH'), blah=blah(billingNumber=u''), blah=None, id=u'f10648fa-e18a-52e6-92cc-a2c0e3cb4a92')"

如何在Javascript中获取名称John Doe)?我自己一直在寻找解决方案,但无济于事。

2 个答案:

答案 0 :(得分:1)

您有2个选项。使用RegEx:

/name=u'(.*?)'/

获取 1st Capture Group 中的数据,如下所示:

string.match(/name=u'(.*?)'/)[1]

整个匹配存储在索引[0],但这将是name=u'John Doe'

或者按'拆分并获取第一位数据(仅当名称是第一个参数时才有效):

string.split("'")[1]

请注意,索引[0]的数据为Account(name=u

var string = "Account(name=u'John Doe', firstName=None, accountNumber=None, middleName=None, lastName=None, blah=None, blah=None, blah=Identification(blah=u'None', blah=u'2016-02-29', blah=1, blah=u'2313', name=u'Passport'), blah=Address(address1=u'None', country=u'PH'), blah=blah(billingNumber=u''), blah=None, id=u'f10648fa-e18a-52e6-92cc-a2c0e3cb4a92')"

var split = string.split("'")[1]
var regex = string.match(/name=u'(.*?)'/)[1]

document.write('Using .split() - ' + split + '<br>')
document.write('Using RegEx - ' + regex + '<br>')

答案 1 :(得分:0)

您可以尝试split(),下面就是一个例子。

&#13;
&#13;
var text = "Account(name=u'John Doe', firstName=None, accountNumber=None, middleName=None, lastName=None, bankDetail=None, contactNumber=None, identification=Identification(placeOfIssue=u'None', expiryDate=u'2016-02-29', type=1, number=u'2313', name=u'Passport'), address=Address(address1=u'None', country=u'PH'), billsPaymentDetail=BillsPaymentDetail(billingNumber=u''), smartMoneyDetail=None, id=u'f10648fa-e18a-52e6-92cc-a2c0e3cb4a92')"

document.write(text.split("'")[1]);
&#13;
&#13;
&#13;