使用正则表达式获取部分字符串 [英] Get part of the string using regexp

查看:83
本文介绍了使用正则表达式获取部分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,它可以包含如下文本:

I've a strings, which can have a text like:

'some text user#t12# some text'
'username#John# some text'
'some text usersurname#Malks#'
'userphoto#1.jpg#'

如何在 # 和 # 符号之间获取文本?

How do I get a text between # and # symbols?

要搜索的字符串部分有一个典型的结构 - type#variable#

There's a typical structure of the part of the string to search for - type#variable#

type 是一个 JS 变量 type,放在第一个 # 之前.

type is a JS variable type, it's placed before the first #.

variable 是我需要获取的文本.

variable is a text that I need to get.

我正在寻找一个正则表达式,它返回 variable,在 #...# 之间.

I'm searching for a regexp, that return variable, that is between #...#.

问题是,我对正则表达式不太熟悉,你能帮我吗?

The problem is, I'm not too familiar with regexp, can you help me please?

推荐答案

您需要使用捕获组,基本上在正则表达式中括号中的任何内容都将成为 cpature 组的一部分,在这种情况下,您希望捕获之间的所有字符两个哈希.任意数量的正则表达式是 .* 所以这是你想要在两个散列之间捕获的内容.执行后,您将在数组中找到第二个匹配项(第一个将是带有散列的字符串.

You need to use capture groups, basically in a regex anything in brackets will be part of the cpature group, in this case you want to capture all the characters between two hashes. The any amount of characters regex is .* so this is what you want to capture between two hashes. Once you execute it you will find the match as second in the array (the first will be the string with the hashes.

var type = "";
var myString = "some text user#t12# some text";
var myRegexp = new RegExp(type+"#(.*)#","g");
var match = myRegexp.exec(myString);
alert(match[1]);  // t12

哈希之间的任何其他匹配都将在 match[2]..match[n]

any other matches between hashes will be in match[2].. match[n]

这篇关于使用正则表达式获取部分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆