使用正则表达式获取部分字符串

编程入门 行业动态 更新时间:2024-10-25 16:17:43
本文介绍了使用正则表达式获取部分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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]

更多推荐

使用正则表达式获取部分字符串

本文发布于:2023-11-03 12:57:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555193.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!