[英]How to split text contain multiple symbol into an array in react native?
I'm new in react native and not yet familiar with regex, i want to split text using regex. 我是React Native的新手,还不熟悉regex,我想使用regex分割文本。
I just can handle one symbol of text in react native using below code: 我只能使用以下代码在本地响应中处理一个文本符号:
mapStringToJSX=(text)=>{
let rendering=[]
const nyoba = text.split(/@(.*?)@/g)
nyoba.map((val,index)=>{
//handle split text
})
return(
<Text>
{rendering}
</Text>
)
}
Here i can split any text contain @
on first and last text, but the symbol is gone 在这里,我可以分割在第一个和最后一个文本上包含@
任何文本,但是符号不见了
For example: 例如:
string = "sample text contain @at first and last text@"
output = ["sample text contain ", "at first and last text", ""]
My question is how can i handle if a string
contain more than one symbol and keep the symbol exist in array? 我的问题是如何处理一个string
包含多个符号并使该符号存在于数组中?
Expected Result: 预期结果:
string = "I @have@ a text #contain# two sy@mbol@ or @#even more#@"
output = ["I ", "@have@", " a text ", "#contain#", " two sy", "@mbol@", " or ", "@#even more#@", ""]
Since you're already using Regex, you can use character classes and back-references: 由于您已经在使用正则表达式,因此可以使用字符类和反向引用:
If you want to always match the innermost values, without accepting unpaired nested markers 如果要始终匹配最里面的值,而不接受未配对的嵌套标记
([#@])([^#@]*?)\\1
If you want to match the outermost match regardless, use: 如果无论如何都要匹配最外层匹配,请使用:
([#@])(.*?)\\1
Explaining the first (the others are just variations of the middle part): 解释第一个(其他只是中间部分的变体):
([#@])
: A group matching either a # or a @. ([#@])
:匹配#或@的组。 ([^#@]*?)
: Zero or more characters that are not a # or a @ ([^#@]*?)
:零个或多个不是#或@的字符
[^#@]
: The box bracket means "any of", and if the first character is ^
then it means "none of" [^#@]
:方括号表示“任何”,如果第一个字符是^
则表示“无” \\1
: Matches exactly the content of the first capture group (so either a # or a @, but most importantly, if the opening was a @ then it will only match the @, so in cases like foo#bar@lalal
it will not not match bar
because the start and end markers are different) \\1
:与第一个捕获组的内容完全匹配(所以#或@,但是最重要的是,如果开头是@,那么它将仅匹配@,因此在类似foo#bar@lalal
情况下,它将匹配不匹配bar
因为开始和结束标记不同) Also, if you want to test your regular expressions in a more visual way, I highly recommend using Regex101 , it shows you the matches and the full explanation of the regex you write automatically. 另外,如果要以更直观的方式测试正则表达式,我强烈建议使用Regex101 ,它会向您显示匹配项以及自动编写的正则表达式的完整说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.