正则表达式由于Instr而拒绝匹配
时间:2020-03-05 18:39:27 来源:igfitidea点击:
用正则表达式执行" instring"类型函数的最简单方法是什么?例如,由于单个字符(如:
)的存在,我如何拒绝整个字符串?例如:
this
-好的there:is
-由于:
不好
实际上,我如何匹配以下字符串:
//foo/bar/baz[1]/ns:foo2/@attr/text()
对于在不包含名称空间的xpath上进行的任何节点测试?
(/)?(/)([^:/]+)
将匹配节点测试,但包含名称空间前缀,这会导致错误。
解决方案
回答
我不太了解regex语法,但我们不能这样做:
[任何字母数字] \ *:[任何字母数字] \ *
我认为类似的东西应该行不通吗?
回答
匹配:?我认为问题还不够清楚,因为答案非常明显:
if(Regex.Match(":", input)) // reject
回答
我们可能希望\ w是一个"单词"字符。在javadocs中,它被定义为[a-zA-Z_0-9],因此,如果我们也不希望使用下划线,则可能无法正常工作。
回答
是的,我的问题不是很清楚。这是一个解决方案,而不是单次使用正则表达式,而是使用split并执行迭代。它也可以工作,但不那么优雅:
string xpath = "//foo/bar/baz[1]/ns:foo2/@attr/text()"; string[] nodetests = xpath.Split( new char[] { '/' } ); for (int i = 0; i < nodetests.Length; i++) { if (nodetests[i].Length > 0 && Regex.IsMatch( nodetests[i], @"^(\w|\[|\])+$" )) { // does not have a ":", we can manipulate it. } } xpath = String.Join( "/", nodetests );
回答
我仍然不确定我们是否只是想检测Xpath是否包含名称空间,还是要删除对该名称空间的引用。因此,这里有一些示例代码(在C#中)可同时实现这两个功能。
class Program { static void Main(string[] args) { string withNamespace = @"//foo/ns2:bar/baz[1]/ns:foo2/@attr/text()"; string withoutNamespace = @"//foo/bar/baz[1]/foo2/@attr/text()"; ShowStuff(withNamespace); ShowStuff(withoutNamespace); } static void ShowStuff(string input) { Console.WriteLine("'{0}' does {1}contain namespaces", input, ContainsNamespace(input) ? "" : "not "); Console.WriteLine("'{0}' without namespaces is '{1}'", input, StripNamespaces(input)); } static bool ContainsNamespace(string input) { // a namspace must start with a character, but can have characters and numbers // from that point on. return Regex.IsMatch(input, @"/?\w[\w\d]+:\w[\w\d]+/?"); } static string StripNamespaces(string input) { return Regex.Replace(input, @"(/?)\w[\w\d]+:(\w[\w\d]+)(/?)", ""); } }
希望对我们有所帮助!祝你好运。