简体   繁体   English

如何使正则表达式第一次出现效果。 (科特琳)

[英]How to make regular-expression end at first chance. (Kotlin)

Say I have a string that contains a program with notes as follows: 说我有一个字符串,其中包含一个带有注释的程序,如下所示:

var iString = "int i; //A variable \n" +
"//This is a text with notes \n" +
"//Can you remove them? \n" +
"cout<<i; //printing i \n"

I've created a regular expression that would recognize notes: 我创建了一个可以识别注释的正则表达式:

var notes1= ("/"+"(\\s)*"+"/"+"(\\w|[^\\w])*"+"\\n").toRegex()

Problem is when writing var newString = iString.replace(notes1,"") 问题是在编写var newString = iString.replace(notes1,"")

I accept newString to be: "int i; cout<<i \\n" 我接受newString为: "int i; cout<<i \\n"

Instead, the result is: "int i;" 相反,结果是: "int i;"

The regular expression 'devours' the whole string till the last "\\n" while I wanted is to end whenever is gets the chance. 正则表达式“吞噬”整个字符串,直到最后一个"\\n"而我想要的是在有机会时结束。

How do I define it in Kotlin? 如何在Kotlin中定义它?

X* is a greedy quantifier (see Quantifiers (The Java™ Tutorials > Essential Classes > Regular Expressions ). X*是贪婪的量词(请参阅量词(Java™教程>基本类>正则表达式 )。

You can use X*? 您可以使用X*? instead which is a reluctant quantifier: 相反,这是一个勉强的量词:

var iString = "int i; //A variable \n" +
        "//This is a text with notes \n" +
        "//Can you remove them? \n" +
        "cout<<i; //printing i \n"
var notes1= ("/"+"(\\s)*"+"/"+"(\\w|[^\\w])*?"+"\\n").toRegex()
println(iString.replace(notes1, ""))

Output: 输出:

int i; cout<<i; 

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

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