简体   繁体   English

正则表达式获取包含起始字符的字符串

[英]Regular expression to get the string including the starting character

I have a string like this 我有这样的字符串

var str="|Text|Facebook|Twitter|";

I am trying to get any one of the word with its preceding pipe sign so something like 我试图得到任何一个单词与其前面的管道标志,如此类似

|Text or |Facebook or |Twitter |Text|Facebook|Twitter

I thought of below two patterns but they didn't work 我想到了两种模式,但它们没有用

/|Facebook/g  //returned nothing
/^|Facebook/g // returned "Facebook" but I want "|Facebook"

What should I use to get |Facebook ? 我应该用什么来获取|Facebook

The pipe is special character in a regular expression. 管道是正则表达式中的特殊字符。 A|B matches A or B . A|B匹配A B

You have to escape the pipe to match | 你必须逃避管道匹配| literally. 从字面上。

var str = '|Text|Facebook|Twitter|'
str.match(/\|\w+/g) // => ["|Text", "|Facebook", "|Twitter"]

\\w matches any alphabet, digit, _ . \\w匹配任何字母,数字, _

You should escape | 你应该逃避| char: 焦炭:

/\|Facebook/g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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